From 3644a299f61082e55b975c45966f83b9b5e1b63d Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Wed, 3 Sep 2025 00:00:25 +0000 Subject: [PATCH 1/2] feat: added support for service maintained provider PiperOrigin-RevId: 802269281 Source-Link: https://github.com/googleapis/googleapis/commit/65afc22de9b311ccdc38e737cc2e3739608706dd Source-Link: https://github.com/googleapis/googleapis-gen/commit/f7c9511be5a82fc6bed85310f9e7ed390e55eb41 Copy-Tag: eyJwIjoicGFja2FnZXMvZ29vZ2xlLWNsb3VkLWNvbmZpZy8uT3dsQm90LnlhbWwiLCJoIjoiZjdjOTUxMWJlNWE4MmZjNmJlZDg1MzEwZjllN2VkMzkwZTU1ZWI0MSJ9 --- .../google-cloud-config/v1/.coveragerc | 13 + .../google-cloud-config/v1/.flake8 | 34 + .../google-cloud-config/v1/LICENSE | 202 + .../google-cloud-config/v1/MANIFEST.in | 20 + .../google-cloud-config/v1/README.rst | 143 + .../v1/docs/_static/custom.css | 20 + .../v1/docs/_templates/layout.html | 50 + .../google-cloud-config/v1/docs/conf.py | 385 + .../v1/docs/config_v1/config.rst | 10 + .../v1/docs/config_v1/services_.rst | 6 + .../v1/docs/config_v1/types_.rst | 6 + .../google-cloud-config/v1/docs/index.rst | 10 + .../v1/docs/multiprocessing.rst | 7 + .../v1/google/cloud/config/__init__.py | 153 + .../v1/google/cloud/config/gapic_version.py | 16 + .../v1/google/cloud/config/py.typed | 2 + .../v1/google/cloud/config_v1/__init__.py | 154 + .../cloud/config_v1/gapic_metadata.json | 433 + .../google/cloud/config_v1/gapic_version.py | 16 + .../v1/google/cloud/config_v1/py.typed | 2 + .../cloud/config_v1/services/__init__.py | 15 + .../config_v1/services/config/__init__.py | 22 + .../config_v1/services/config/async_client.py | 4004 +++ .../cloud/config_v1/services/config/client.py | 4436 +++ .../cloud/config_v1/services/config/pagers.py | 1000 + .../services/config/transports/README.rst | 9 + .../services/config/transports/__init__.py | 38 + .../services/config/transports/base.py | 661 + .../services/config/transports/grpc.py | 1246 + .../config/transports/grpc_asyncio.py | 1442 + .../services/config/transports/rest.py | 6103 ++++ .../services/config/transports/rest_base.py | 1435 + .../google/cloud/config_v1/types/__init__.py | 146 + .../v1/google/cloud/config_v1/types/config.py | 3309 +++ .../google-cloud-config/v1/mypy.ini | 3 + .../google-cloud-config/v1/noxfile.py | 591 + ...enerated_config_create_deployment_async.py | 61 + ...generated_config_create_deployment_sync.py | 61 + ...1_generated_config_create_preview_async.py | 61 + ...v1_generated_config_create_preview_sync.py | 61 + ...enerated_config_delete_deployment_async.py | 56 + ...generated_config_delete_deployment_sync.py | 56 + ...1_generated_config_delete_preview_async.py | 56 + ...v1_generated_config_delete_preview_sync.py | 56 + ...generated_config_delete_statefile_async.py | 51 + ..._generated_config_delete_statefile_sync.py | 51 + ...onfig_export_deployment_statefile_async.py | 52 + ...config_export_deployment_statefile_sync.py | 52 + ...generated_config_export_lock_info_async.py | 52 + ..._generated_config_export_lock_info_sync.py | 52 + ...ated_config_export_preview_result_async.py | 52 + ...rated_config_export_preview_result_sync.py | 52 + ..._config_export_revision_statefile_async.py | 52 + ...d_config_export_revision_statefile_sync.py | 52 + ...1_generated_config_get_deployment_async.py | 52 + ...v1_generated_config_get_deployment_sync.py | 52 + ...g_v1_generated_config_get_preview_async.py | 52 + ...ig_v1_generated_config_get_preview_sync.py | 52 + ..._v1_generated_config_get_resource_async.py | 52 + ...erated_config_get_resource_change_async.py | 52 + ...nerated_config_get_resource_change_sync.py | 52 + ...nerated_config_get_resource_drift_async.py | 52 + ...enerated_config_get_resource_drift_sync.py | 52 + ...g_v1_generated_config_get_resource_sync.py | 52 + ..._v1_generated_config_get_revision_async.py | 52 + ...g_v1_generated_config_get_revision_sync.py | 52 + ...ated_config_get_terraform_version_async.py | 52 + ...rated_config_get_terraform_version_sync.py | 52 + ...generated_config_import_statefile_async.py | 53 + ..._generated_config_import_statefile_sync.py | 53 + ...generated_config_list_deployments_async.py | 53 + ..._generated_config_list_deployments_sync.py | 53 + ...v1_generated_config_list_previews_async.py | 53 + ..._v1_generated_config_list_previews_sync.py | 53 + ...ated_config_list_resource_changes_async.py | 53 + ...rated_config_list_resource_changes_sync.py | 53 + ...rated_config_list_resource_drifts_async.py | 53 + ...erated_config_list_resource_drifts_sync.py | 53 + ...1_generated_config_list_resources_async.py | 53 + ...v1_generated_config_list_resources_sync.py | 53 + ...1_generated_config_list_revisions_async.py | 53 + ...v1_generated_config_list_revisions_sync.py | 53 + ...ed_config_list_terraform_versions_async.py | 53 + ...ted_config_list_terraform_versions_sync.py | 53 + ..._generated_config_lock_deployment_async.py | 56 + ...1_generated_config_lock_deployment_sync.py | 56 + ...enerated_config_unlock_deployment_async.py | 57 + ...generated_config_unlock_deployment_sync.py | 57 + ...enerated_config_update_deployment_async.py | 59 + ...generated_config_update_deployment_sync.py | 59 + ...ippet_metadata_google.cloud.config.v1.json | 4380 +++ .../v1/scripts/fixup_config_v1_keywords.py | 202 + .../google-cloud-config/v1/setup.py | 99 + .../v1/testing/constraints-3.10.txt | 7 + .../v1/testing/constraints-3.11.txt | 7 + .../v1/testing/constraints-3.12.txt | 7 + .../v1/testing/constraints-3.13.txt | 12 + .../v1/testing/constraints-3.7.txt | 11 + .../v1/testing/constraints-3.8.txt | 7 + .../v1/testing/constraints-3.9.txt | 7 + .../google-cloud-config/v1/tests/__init__.py | 16 + .../v1/tests/unit/__init__.py | 16 + .../v1/tests/unit/gapic/__init__.py | 16 + .../v1/tests/unit/gapic/config_v1/__init__.py | 16 + .../tests/unit/gapic/config_v1/test_config.py | 23350 ++++++++++++++++ 105 files changed, 57201 insertions(+) create mode 100644 owl-bot-staging/google-cloud-config/v1/.coveragerc create mode 100644 owl-bot-staging/google-cloud-config/v1/.flake8 create mode 100644 owl-bot-staging/google-cloud-config/v1/LICENSE create mode 100644 owl-bot-staging/google-cloud-config/v1/MANIFEST.in create mode 100644 owl-bot-staging/google-cloud-config/v1/README.rst create mode 100644 owl-bot-staging/google-cloud-config/v1/docs/_static/custom.css create mode 100644 owl-bot-staging/google-cloud-config/v1/docs/_templates/layout.html create mode 100644 owl-bot-staging/google-cloud-config/v1/docs/conf.py create mode 100644 owl-bot-staging/google-cloud-config/v1/docs/config_v1/config.rst create mode 100644 owl-bot-staging/google-cloud-config/v1/docs/config_v1/services_.rst create mode 100644 owl-bot-staging/google-cloud-config/v1/docs/config_v1/types_.rst create mode 100644 owl-bot-staging/google-cloud-config/v1/docs/index.rst create mode 100644 owl-bot-staging/google-cloud-config/v1/docs/multiprocessing.rst create mode 100644 owl-bot-staging/google-cloud-config/v1/google/cloud/config/__init__.py create mode 100644 owl-bot-staging/google-cloud-config/v1/google/cloud/config/gapic_version.py create mode 100644 owl-bot-staging/google-cloud-config/v1/google/cloud/config/py.typed create mode 100644 owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/__init__.py create mode 100644 owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/gapic_metadata.json create mode 100644 owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/gapic_version.py create mode 100644 owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/py.typed create mode 100644 owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/__init__.py create mode 100644 owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/__init__.py create mode 100644 owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/async_client.py create mode 100644 owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/client.py create mode 100644 owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/pagers.py create mode 100644 owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/transports/README.rst create mode 100644 owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/transports/__init__.py create mode 100644 owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/transports/base.py create mode 100644 owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/transports/grpc.py create mode 100644 owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/transports/rest.py create mode 100644 owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/transports/rest_base.py create mode 100644 owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/types/__init__.py create mode 100644 owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/types/config.py create mode 100644 owl-bot-staging/google-cloud-config/v1/mypy.ini create mode 100644 owl-bot-staging/google-cloud-config/v1/noxfile.py create mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_create_deployment_async.py create mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_create_deployment_sync.py create mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_create_preview_async.py create mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_create_preview_sync.py create mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_delete_deployment_async.py create mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_delete_deployment_sync.py create mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_delete_preview_async.py create mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_delete_preview_sync.py create mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_delete_statefile_async.py create mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_delete_statefile_sync.py create mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_export_deployment_statefile_async.py create mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_export_deployment_statefile_sync.py create mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_export_lock_info_async.py create mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_export_lock_info_sync.py create mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_export_preview_result_async.py create mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_export_preview_result_sync.py create mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_export_revision_statefile_async.py create mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_export_revision_statefile_sync.py create mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_deployment_async.py create mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_deployment_sync.py create mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_preview_async.py create mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_preview_sync.py create mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_resource_async.py create mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_resource_change_async.py create mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_resource_change_sync.py create mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_resource_drift_async.py create mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_resource_drift_sync.py create mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_resource_sync.py create mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_revision_async.py create mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_revision_sync.py create mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_terraform_version_async.py create mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_terraform_version_sync.py create mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_import_statefile_async.py create mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_import_statefile_sync.py create mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_deployments_async.py create mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_deployments_sync.py create mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_previews_async.py create mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_previews_sync.py create mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_resource_changes_async.py create mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_resource_changes_sync.py create mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_resource_drifts_async.py create mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_resource_drifts_sync.py create mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_resources_async.py create mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_resources_sync.py create mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_revisions_async.py create mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_revisions_sync.py create mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_terraform_versions_async.py create mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_terraform_versions_sync.py create mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_lock_deployment_async.py create mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_lock_deployment_sync.py create mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_unlock_deployment_async.py create mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_unlock_deployment_sync.py create mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_update_deployment_async.py create mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_update_deployment_sync.py create mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/snippet_metadata_google.cloud.config.v1.json create mode 100644 owl-bot-staging/google-cloud-config/v1/scripts/fixup_config_v1_keywords.py create mode 100644 owl-bot-staging/google-cloud-config/v1/setup.py create mode 100644 owl-bot-staging/google-cloud-config/v1/testing/constraints-3.10.txt create mode 100644 owl-bot-staging/google-cloud-config/v1/testing/constraints-3.11.txt create mode 100644 owl-bot-staging/google-cloud-config/v1/testing/constraints-3.12.txt create mode 100644 owl-bot-staging/google-cloud-config/v1/testing/constraints-3.13.txt create mode 100644 owl-bot-staging/google-cloud-config/v1/testing/constraints-3.7.txt create mode 100644 owl-bot-staging/google-cloud-config/v1/testing/constraints-3.8.txt create mode 100644 owl-bot-staging/google-cloud-config/v1/testing/constraints-3.9.txt create mode 100644 owl-bot-staging/google-cloud-config/v1/tests/__init__.py create mode 100644 owl-bot-staging/google-cloud-config/v1/tests/unit/__init__.py create mode 100644 owl-bot-staging/google-cloud-config/v1/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/google-cloud-config/v1/tests/unit/gapic/config_v1/__init__.py create mode 100644 owl-bot-staging/google-cloud-config/v1/tests/unit/gapic/config_v1/test_config.py diff --git a/owl-bot-staging/google-cloud-config/v1/.coveragerc b/owl-bot-staging/google-cloud-config/v1/.coveragerc new file mode 100644 index 000000000000..01f0878da1cf --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/config/__init__.py + google/cloud/config/gapic_version.py +exclude_lines = + # Re-enable the standard pragma + pragma: NO COVER + # Ignore debug-only repr + def __repr__ diff --git a/owl-bot-staging/google-cloud-config/v1/.flake8 b/owl-bot-staging/google-cloud-config/v1/.flake8 new file mode 100644 index 000000000000..90316de21489 --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/.flake8 @@ -0,0 +1,34 @@ +# -*- 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. +# +[flake8] +# TODO(https://github.com/googleapis/gapic-generator-python/issues/2333): +# Resolve flake8 lint issues +ignore = E203, E231, E266, E501, W503 +exclude = + # TODO(https://github.com/googleapis/gapic-generator-python/issues/2333): + # Ensure that generated code passes flake8 lint + **/gapic/** + **/services/** + **/types/** + # Exclude Protobuf gencode + *_pb2.py + + # Standard linting exemptions. + **/.nox/** + __pycache__, + .git, + *.pyc, + conf.py diff --git a/owl-bot-staging/google-cloud-config/v1/LICENSE b/owl-bot-staging/google-cloud-config/v1/LICENSE new file mode 100644 index 000000000000..d64569567334 --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT 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/owl-bot-staging/google-cloud-config/v1/MANIFEST.in b/owl-bot-staging/google-cloud-config/v1/MANIFEST.in new file mode 100644 index 000000000000..dae249ec8976 --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/MANIFEST.in @@ -0,0 +1,20 @@ +# -*- 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. +# +include README.rst LICENSE +recursive-include google *.py *.pyi *.json *.proto py.typed +recursive-include tests * +global-exclude *.py[co] +global-exclude __pycache__ diff --git a/owl-bot-staging/google-cloud-config/v1/README.rst b/owl-bot-staging/google-cloud-config/v1/README.rst new file mode 100644 index 000000000000..80bc4c51622b --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/README.rst @@ -0,0 +1,143 @@ +Python Client for Google Cloud Config API +================================================= + +Quick Start +----------- + +In order to use this library, you first need to go through the following steps: + +1. `Select or create a Cloud Platform project.`_ +2. `Enable billing for your project.`_ +3. Enable the Google Cloud Config API. +4. `Setup Authentication.`_ + +.. _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 +.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html + +Installation +~~~~~~~~~~~~ + +Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to +create isolated Python environments. The basic problem it addresses is one of +dependencies and versions, and indirectly permissions. + +With `virtualenv`_, it's possible to install this library without needing system +install permissions, and without clashing with the installed system +dependencies. + +.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ + + +Mac/Linux +^^^^^^^^^ + +.. code-block:: console + + python3 -m venv + source /bin/activate + /bin/pip install /path/to/library + + +Windows +^^^^^^^ + +.. code-block:: console + + python3 -m venv + \Scripts\activate + \Scripts\pip.exe install \path\to\library + + +Logging +------- + +This library uses the standard Python :code:`logging` functionality to log some RPC events that could be of interest for debugging and monitoring purposes. +Note the following: + +#. Logs may contain sensitive information. Take care to **restrict access to the logs** if they are saved, whether it be on local storage or on Google Cloud Logging. +#. Google may refine the occurrence, level, and content of various log messages in this library without flagging such changes as breaking. **Do not depend on immutability of the logging events**. +#. By default, the logging events from this library are not handled. You must **explicitly configure log handling** using one of the mechanisms below. + + +Simple, environment-based configuration +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +To enable logging for this library without any changes in your code, set the :code:`GOOGLE_SDK_PYTHON_LOGGING_SCOPE` environment variable to a valid Google +logging scope. This configures handling of logging events (at level :code:`logging.DEBUG` or higher) from this library in a default manner, emitting the logged +messages in a structured format. It does not currently allow customizing the logging levels captured nor the handlers, formatters, etc. used for any logging +event. + +A logging scope is a period-separated namespace that begins with :code:`google`, identifying the Python module or package to log. + +- Valid logging scopes: :code:`google`, :code:`google.cloud.asset.v1`, :code:`google.api`, :code:`google.auth`, etc. +- Invalid logging scopes: :code:`foo`, :code:`123`, etc. + +**NOTE**: If the logging scope is invalid, the library does not set up any logging handlers. + + +Examples +^^^^^^^^ + +- Enabling the default handler for all Google-based loggers + +.. code-block:: console + + export GOOGLE_SDK_PYTHON_LOGGING_SCOPE=google + +- Enabling the default handler for a specific Google module (for a client library called :code:`library_v1`): + +.. code-block:: console + + export GOOGLE_SDK_PYTHON_LOGGING_SCOPE=google.cloud.library_v1 + + +Advanced, code-based configuration +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +You can also configure a valid logging scope using Python's standard `logging` mechanism. + + +Examples +^^^^^^^^ + +- Configuring a handler for all Google-based loggers + +.. code-block:: python + + import logging + + from google.cloud.translate_v3 import translate + + base_logger = logging.getLogger("google") + base_logger.addHandler(logging.StreamHandler()) + base_logger.setLevel(logging.DEBUG) + +- Configuring a handler for a specific Google module (for a client library called :code:`library_v1`): + +.. code-block:: python + + import logging + + from google.cloud.translate_v3 import translate + + base_logger = logging.getLogger("google.cloud.library_v1") + base_logger.addHandler(logging.StreamHandler()) + base_logger.setLevel(logging.DEBUG) + + +Logging details +~~~~~~~~~~~~~~~ + +#. Regardless of which of the mechanisms above you use to configure logging for this library, by default logging events are not propagated up to the root + logger from the `google`-level logger. If you need the events to be propagated to the root logger, you must explicitly set + :code:`logging.getLogger("google").propagate = True` in your code. +#. You can mix the different logging configurations above for different Google modules. For example, you may want use a code-based logging configuration for + one library, but decide you need to also set up environment-based logging configuration for another library. + + #. If you attempt to use both code-based and environment-based configuration for the same module, the environment-based configuration will be ineffectual + if the code -based configuration gets applied first. + +#. The Google-specific logging configurations (default handlers for environment-based configuration; not propagating logging events to the root logger) get + executed the first time *any* client library is instantiated in your application, and only if the affected loggers have not been previously configured. + (This is the reason for 2.i. above.) diff --git a/owl-bot-staging/google-cloud-config/v1/docs/_static/custom.css b/owl-bot-staging/google-cloud-config/v1/docs/_static/custom.css new file mode 100644 index 000000000000..b0a295464b23 --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/docs/_static/custom.css @@ -0,0 +1,20 @@ +div#python2-eol { + border-color: red; + border-width: medium; +} + +/* Ensure minimum width for 'Parameters' / 'Returns' column */ +dl.field-list > dt { + min-width: 100px +} + +/* Insert space between methods for readability */ +dl.method { + padding-top: 10px; + padding-bottom: 10px +} + +/* Insert empty space between classes */ +dl.class { + padding-bottom: 50px +} diff --git a/owl-bot-staging/google-cloud-config/v1/docs/_templates/layout.html b/owl-bot-staging/google-cloud-config/v1/docs/_templates/layout.html new file mode 100644 index 000000000000..95e9c77fcfe1 --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/docs/_templates/layout.html @@ -0,0 +1,50 @@ + +{% extends "!layout.html" %} +{%- block content %} +{%- if theme_fixed_sidebar|lower == 'true' %} +
+ {{ sidebar() }} + {%- block document %} +
+ {%- if render_sidebar %} +
+ {%- endif %} + + {%- block relbar_top %} + {%- if theme_show_relbar_top|tobool %} + + {%- endif %} + {% endblock %} + +
+
+ As of January 1, 2020 this library no longer supports Python 2 on the latest released version. + Library versions released prior to that date will continue to be available. For more information please + visit Python 2 support on Google Cloud. +
+ {% block body %} {% endblock %} +
+ + {%- block relbar_bottom %} + {%- if theme_show_relbar_bottom|tobool %} + + {%- endif %} + {% endblock %} + + {%- if render_sidebar %} +
+ {%- endif %} +
+ {%- endblock %} +
+
+{%- else %} +{{ super() }} +{%- endif %} +{%- endblock %} diff --git a/owl-bot-staging/google-cloud-config/v1/docs/conf.py b/owl-bot-staging/google-cloud-config/v1/docs/conf.py new file mode 100644 index 000000000000..7935eaba9a58 --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/docs/conf.py @@ -0,0 +1,385 @@ +# -*- 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. +# +# +# google-cloud-config documentation build configuration file +# +# This file is execfile()d with the current directory set to its +# containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +import sys +import os +import shlex + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +sys.path.insert(0, os.path.abspath("..")) + +# For plugins that can not read conf.py. +# See also: https://github.com/docascode/sphinx-docfx-yaml/issues/85 +sys.path.insert(0, os.path.abspath(".")) + +__version__ = "" + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +needs_sphinx = "4.5.0" + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ + "sphinx.ext.autodoc", + "sphinx.ext.autosummary", + "sphinx.ext.intersphinx", + "sphinx.ext.coverage", + "sphinx.ext.doctest", + "sphinx.ext.napoleon", + "sphinx.ext.todo", + "sphinx.ext.viewcode", + "recommonmark", +] + +# autodoc/autosummary flags +autoclass_content = "both" +autodoc_default_options = {"members": True} +autosummary_generate = True + + +# Add any paths that contain templates here, relative to this directory. +templates_path = ["_templates"] + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +# source_suffix = ['.rst', '.md'] +source_suffix = [".rst", ".md"] + +# The encoding of source files. +# source_encoding = 'utf-8-sig' + +# The root toctree document. +root_doc = "index" + +# General information about the project. +project = u"google-cloud-config" +copyright = u"2025, Google, LLC" +author = u"Google APIs" + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The full version, including alpha/beta/rc tags. +release = __version__ +# The short X.Y version. +version = ".".join(release.split(".")[0:2]) + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +# today = '' +# Else, today_fmt is used as the format for a strftime call. +# today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = [ + "_build", + "**/.nox/**/*", + "samples/AUTHORING_GUIDE.md", + "samples/CONTRIBUTING.md", + "samples/snippets/README.rst", +] + +# The reST default role (used for this markup: `text`) to use for all +# documents. +# default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +# add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +# add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +# show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = "sphinx" + +# A list of ignored prefixes for module index sorting. +# modindex_common_prefix = [] + +# If true, keep warnings as "system message" paragraphs in the built documents. +# keep_warnings = False + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = True + + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = "alabaster" + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +html_theme_options = { + "description": "Google Cloud Client Libraries for google-cloud-config", + "github_user": "googleapis", + "github_repo": "google-cloud-python", + "github_banner": True, + "font_family": "'Roboto', Georgia, sans", + "head_font_family": "'Roboto', Georgia, serif", + "code_font_family": "'Roboto Mono', 'Consolas', monospace", +} + +# Add any paths that contain custom themes here, relative to this directory. +# html_theme_path = [] + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +# html_title = None + +# A shorter title for the navigation bar. Default is the same as html_title. +# html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +# html_logo = None + +# The name of an image file (within the static path) to use as favicon of the +# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +# html_favicon = None + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ["_static"] + +# Add any extra paths that contain custom files (such as robots.txt or +# .htaccess) here, relative to this directory. These files are copied +# directly to the root of the documentation. +# html_extra_path = [] + +# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, +# using the given strftime format. +# html_last_updated_fmt = '%b %d, %Y' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +# html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +# html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +# html_additional_pages = {} + +# If false, no module index is generated. +# html_domain_indices = True + +# If false, no index is generated. +# html_use_index = True + +# If true, the index is split into individual pages for each letter. +# html_split_index = False + +# If true, links to the reST sources are added to the pages. +# html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +# html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. +# html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +# html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +# html_file_suffix = None + +# Language to be used for generating the HTML full-text search index. +# Sphinx supports the following languages: +# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' +# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' +# html_search_language = 'en' + +# A dictionary with options for the search language support, empty by default. +# Now only 'ja' uses this config value +# html_search_options = {'type': 'default'} + +# The name of a javascript file (relative to the configuration directory) that +# implements a search results scorer. If empty, the default will be used. +# html_search_scorer = 'scorer.js' + +# Output file base name for HTML help builder. +htmlhelp_basename = "google-cloud-config-doc" + +# -- Options for warnings ------------------------------------------------------ + + +suppress_warnings = [ + # Temporarily suppress this to avoid "more than one target found for + # cross-reference" warning, which are intractable for us to avoid while in + # a mono-repo. + # See https://github.com/sphinx-doc/sphinx/blob + # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 + "ref.python" +] + +# -- Options for LaTeX output --------------------------------------------- + +latex_elements = { + # The paper size ('letterpaper' or 'a4paper'). + # 'papersize': 'letterpaper', + # The font size ('10pt', '11pt' or '12pt'). + # 'pointsize': '10pt', + # Additional stuff for the LaTeX preamble. + # 'preamble': '', + # Latex figure (float) alignment + # 'figure_align': 'htbp', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + ( + root_doc, + "google-cloud-config.tex", + u"google-cloud-config Documentation", + author, + "manual", + ) +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +# latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +# latex_use_parts = False + +# If true, show page references after internal links. +# latex_show_pagerefs = False + +# If true, show URL addresses after external links. +# latex_show_urls = False + +# Documents to append as an appendix to all manuals. +# latex_appendices = [] + +# If false, no module index is generated. +# latex_domain_indices = True + + +# -- Options for manual page output --------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + ( + root_doc, + "google-cloud-config", + "google-cloud-config Documentation", + [author], + 1, + ) +] + +# If true, show URL addresses after external links. +# man_show_urls = False + + +# -- Options for Texinfo output ------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + ( + root_doc, + "google-cloud-config", + "google-cloud-config Documentation", + author, + "google-cloud-config", + "google-cloud-config Library", + "APIs", + ) +] + +# Documents to append as an appendix to all manuals. +# texinfo_appendices = [] + +# If false, no module index is generated. +# texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +# texinfo_show_urls = 'footnote' + +# If true, do not generate a @detailmenu in the "Top" node's menu. +# texinfo_no_detailmenu = False + + +# Example configuration for intersphinx: refer to the Python standard library. +intersphinx_mapping = { + "python": ("https://python.readthedocs.org/en/latest/", None), + "google-auth": ("https://googleapis.dev/python/google-auth/latest/", None), + "google.api_core": ( + "https://googleapis.dev/python/google-api-core/latest/", + None, + ), + "grpc": ("https://grpc.github.io/grpc/python/", None), + "proto-plus": ("https://proto-plus-python.readthedocs.io/en/latest/", None), + "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), +} + + +# Napoleon settings +napoleon_google_docstring = True +napoleon_numpy_docstring = True +napoleon_include_private_with_doc = False +napoleon_include_special_with_doc = True +napoleon_use_admonition_for_examples = False +napoleon_use_admonition_for_notes = False +napoleon_use_admonition_for_references = False +napoleon_use_ivar = False +napoleon_use_param = True +napoleon_use_rtype = True diff --git a/owl-bot-staging/google-cloud-config/v1/docs/config_v1/config.rst b/owl-bot-staging/google-cloud-config/v1/docs/config_v1/config.rst new file mode 100644 index 000000000000..7ad09d4ba002 --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/docs/config_v1/config.rst @@ -0,0 +1,10 @@ +Config +------------------------ + +.. automodule:: google.cloud.config_v1.services.config + :members: + :inherited-members: + +.. automodule:: google.cloud.config_v1.services.config.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-cloud-config/v1/docs/config_v1/services_.rst b/owl-bot-staging/google-cloud-config/v1/docs/config_v1/services_.rst new file mode 100644 index 000000000000..51dabd45ae67 --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/docs/config_v1/services_.rst @@ -0,0 +1,6 @@ +Services for Google Cloud Config v1 API +======================================= +.. toctree:: + :maxdepth: 2 + + config diff --git a/owl-bot-staging/google-cloud-config/v1/docs/config_v1/types_.rst b/owl-bot-staging/google-cloud-config/v1/docs/config_v1/types_.rst new file mode 100644 index 000000000000..33bb93d6c861 --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/docs/config_v1/types_.rst @@ -0,0 +1,6 @@ +Types for Google Cloud Config v1 API +==================================== + +.. automodule:: google.cloud.config_v1.types + :members: + :show-inheritance: diff --git a/owl-bot-staging/google-cloud-config/v1/docs/index.rst b/owl-bot-staging/google-cloud-config/v1/docs/index.rst new file mode 100644 index 000000000000..0bd88733b91c --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/docs/index.rst @@ -0,0 +1,10 @@ +.. include:: multiprocessing.rst + + +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + config_v1/services_ + config_v1/types_ diff --git a/owl-bot-staging/google-cloud-config/v1/docs/multiprocessing.rst b/owl-bot-staging/google-cloud-config/v1/docs/multiprocessing.rst new file mode 100644 index 000000000000..536d17b2ea65 --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/docs/multiprocessing.rst @@ -0,0 +1,7 @@ +.. note:: + + Because this client uses :mod:`grpc` library, it is safe to + share instances across threads. In multiprocessing scenarios, the best + practice is to create client instances *after* the invocation of + :func:`os.fork` by :class:`multiprocessing.pool.Pool` or + :class:`multiprocessing.Process`. diff --git a/owl-bot-staging/google-cloud-config/v1/google/cloud/config/__init__.py b/owl-bot-staging/google-cloud-config/v1/google/cloud/config/__init__.py new file mode 100644 index 000000000000..79797d85e9c1 --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/google/cloud/config/__init__.py @@ -0,0 +1,153 @@ +# -*- 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. +# +from google.cloud.config import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.cloud.config_v1.services.config.client import ConfigClient +from google.cloud.config_v1.services.config.async_client import ConfigAsyncClient + +from google.cloud.config_v1.types.config import ApplyResults +from google.cloud.config_v1.types.config import CreateDeploymentRequest +from google.cloud.config_v1.types.config import CreatePreviewRequest +from google.cloud.config_v1.types.config import DeleteDeploymentRequest +from google.cloud.config_v1.types.config import DeletePreviewRequest +from google.cloud.config_v1.types.config import DeleteStatefileRequest +from google.cloud.config_v1.types.config import Deployment +from google.cloud.config_v1.types.config import DeploymentOperationMetadata +from google.cloud.config_v1.types.config import ExportDeploymentStatefileRequest +from google.cloud.config_v1.types.config import ExportLockInfoRequest +from google.cloud.config_v1.types.config import ExportPreviewResultRequest +from google.cloud.config_v1.types.config import ExportPreviewResultResponse +from google.cloud.config_v1.types.config import ExportRevisionStatefileRequest +from google.cloud.config_v1.types.config import GetDeploymentRequest +from google.cloud.config_v1.types.config import GetPreviewRequest +from google.cloud.config_v1.types.config import GetResourceChangeRequest +from google.cloud.config_v1.types.config import GetResourceDriftRequest +from google.cloud.config_v1.types.config import GetResourceRequest +from google.cloud.config_v1.types.config import GetRevisionRequest +from google.cloud.config_v1.types.config import GetTerraformVersionRequest +from google.cloud.config_v1.types.config import GitSource +from google.cloud.config_v1.types.config import ImportStatefileRequest +from google.cloud.config_v1.types.config import ListDeploymentsRequest +from google.cloud.config_v1.types.config import ListDeploymentsResponse +from google.cloud.config_v1.types.config import ListPreviewsRequest +from google.cloud.config_v1.types.config import ListPreviewsResponse +from google.cloud.config_v1.types.config import ListResourceChangesRequest +from google.cloud.config_v1.types.config import ListResourceChangesResponse +from google.cloud.config_v1.types.config import ListResourceDriftsRequest +from google.cloud.config_v1.types.config import ListResourceDriftsResponse +from google.cloud.config_v1.types.config import ListResourcesRequest +from google.cloud.config_v1.types.config import ListResourcesResponse +from google.cloud.config_v1.types.config import ListRevisionsRequest +from google.cloud.config_v1.types.config import ListRevisionsResponse +from google.cloud.config_v1.types.config import ListTerraformVersionsRequest +from google.cloud.config_v1.types.config import ListTerraformVersionsResponse +from google.cloud.config_v1.types.config import LockDeploymentRequest +from google.cloud.config_v1.types.config import LockInfo +from google.cloud.config_v1.types.config import OperationMetadata +from google.cloud.config_v1.types.config import Preview +from google.cloud.config_v1.types.config import PreviewArtifacts +from google.cloud.config_v1.types.config import PreviewOperationMetadata +from google.cloud.config_v1.types.config import PreviewResult +from google.cloud.config_v1.types.config import PropertyChange +from google.cloud.config_v1.types.config import PropertyDrift +from google.cloud.config_v1.types.config import ProviderConfig +from google.cloud.config_v1.types.config import Resource +from google.cloud.config_v1.types.config import ResourceCAIInfo +from google.cloud.config_v1.types.config import ResourceChange +from google.cloud.config_v1.types.config import ResourceChangeTerraformInfo +from google.cloud.config_v1.types.config import ResourceDrift +from google.cloud.config_v1.types.config import ResourceDriftTerraformInfo +from google.cloud.config_v1.types.config import ResourceTerraformInfo +from google.cloud.config_v1.types.config import Revision +from google.cloud.config_v1.types.config import Statefile +from google.cloud.config_v1.types.config import TerraformBlueprint +from google.cloud.config_v1.types.config import TerraformError +from google.cloud.config_v1.types.config import TerraformOutput +from google.cloud.config_v1.types.config import TerraformVariable +from google.cloud.config_v1.types.config import TerraformVersion +from google.cloud.config_v1.types.config import UnlockDeploymentRequest +from google.cloud.config_v1.types.config import UpdateDeploymentRequest +from google.cloud.config_v1.types.config import QuotaValidation + +__all__ = ('ConfigClient', + 'ConfigAsyncClient', + 'ApplyResults', + 'CreateDeploymentRequest', + 'CreatePreviewRequest', + 'DeleteDeploymentRequest', + 'DeletePreviewRequest', + 'DeleteStatefileRequest', + 'Deployment', + 'DeploymentOperationMetadata', + 'ExportDeploymentStatefileRequest', + 'ExportLockInfoRequest', + 'ExportPreviewResultRequest', + 'ExportPreviewResultResponse', + 'ExportRevisionStatefileRequest', + 'GetDeploymentRequest', + 'GetPreviewRequest', + 'GetResourceChangeRequest', + 'GetResourceDriftRequest', + 'GetResourceRequest', + 'GetRevisionRequest', + 'GetTerraformVersionRequest', + 'GitSource', + 'ImportStatefileRequest', + 'ListDeploymentsRequest', + 'ListDeploymentsResponse', + 'ListPreviewsRequest', + 'ListPreviewsResponse', + 'ListResourceChangesRequest', + 'ListResourceChangesResponse', + 'ListResourceDriftsRequest', + 'ListResourceDriftsResponse', + 'ListResourcesRequest', + 'ListResourcesResponse', + 'ListRevisionsRequest', + 'ListRevisionsResponse', + 'ListTerraformVersionsRequest', + 'ListTerraformVersionsResponse', + 'LockDeploymentRequest', + 'LockInfo', + 'OperationMetadata', + 'Preview', + 'PreviewArtifacts', + 'PreviewOperationMetadata', + 'PreviewResult', + 'PropertyChange', + 'PropertyDrift', + 'ProviderConfig', + 'Resource', + 'ResourceCAIInfo', + 'ResourceChange', + 'ResourceChangeTerraformInfo', + 'ResourceDrift', + 'ResourceDriftTerraformInfo', + 'ResourceTerraformInfo', + 'Revision', + 'Statefile', + 'TerraformBlueprint', + 'TerraformError', + 'TerraformOutput', + 'TerraformVariable', + 'TerraformVersion', + 'UnlockDeploymentRequest', + 'UpdateDeploymentRequest', + 'QuotaValidation', +) diff --git a/owl-bot-staging/google-cloud-config/v1/google/cloud/config/gapic_version.py b/owl-bot-staging/google-cloud-config/v1/google/cloud/config/gapic_version.py new file mode 100644 index 000000000000..20a9cd975b02 --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/google/cloud/config/gapic_version.py @@ -0,0 +1,16 @@ +# -*- 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. +# +__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-cloud-config/v1/google/cloud/config/py.typed b/owl-bot-staging/google-cloud-config/v1/google/cloud/config/py.typed new file mode 100644 index 000000000000..f4fe63d2606c --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/google/cloud/config/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-config package uses inline types. diff --git a/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/__init__.py b/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/__init__.py new file mode 100644 index 000000000000..0a5f53709651 --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/__init__.py @@ -0,0 +1,154 @@ +# -*- 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. +# +from google.cloud.config_v1 import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.config import ConfigClient +from .services.config import ConfigAsyncClient + +from .types.config import ApplyResults +from .types.config import CreateDeploymentRequest +from .types.config import CreatePreviewRequest +from .types.config import DeleteDeploymentRequest +from .types.config import DeletePreviewRequest +from .types.config import DeleteStatefileRequest +from .types.config import Deployment +from .types.config import DeploymentOperationMetadata +from .types.config import ExportDeploymentStatefileRequest +from .types.config import ExportLockInfoRequest +from .types.config import ExportPreviewResultRequest +from .types.config import ExportPreviewResultResponse +from .types.config import ExportRevisionStatefileRequest +from .types.config import GetDeploymentRequest +from .types.config import GetPreviewRequest +from .types.config import GetResourceChangeRequest +from .types.config import GetResourceDriftRequest +from .types.config import GetResourceRequest +from .types.config import GetRevisionRequest +from .types.config import GetTerraformVersionRequest +from .types.config import GitSource +from .types.config import ImportStatefileRequest +from .types.config import ListDeploymentsRequest +from .types.config import ListDeploymentsResponse +from .types.config import ListPreviewsRequest +from .types.config import ListPreviewsResponse +from .types.config import ListResourceChangesRequest +from .types.config import ListResourceChangesResponse +from .types.config import ListResourceDriftsRequest +from .types.config import ListResourceDriftsResponse +from .types.config import ListResourcesRequest +from .types.config import ListResourcesResponse +from .types.config import ListRevisionsRequest +from .types.config import ListRevisionsResponse +from .types.config import ListTerraformVersionsRequest +from .types.config import ListTerraformVersionsResponse +from .types.config import LockDeploymentRequest +from .types.config import LockInfo +from .types.config import OperationMetadata +from .types.config import Preview +from .types.config import PreviewArtifacts +from .types.config import PreviewOperationMetadata +from .types.config import PreviewResult +from .types.config import PropertyChange +from .types.config import PropertyDrift +from .types.config import ProviderConfig +from .types.config import Resource +from .types.config import ResourceCAIInfo +from .types.config import ResourceChange +from .types.config import ResourceChangeTerraformInfo +from .types.config import ResourceDrift +from .types.config import ResourceDriftTerraformInfo +from .types.config import ResourceTerraformInfo +from .types.config import Revision +from .types.config import Statefile +from .types.config import TerraformBlueprint +from .types.config import TerraformError +from .types.config import TerraformOutput +from .types.config import TerraformVariable +from .types.config import TerraformVersion +from .types.config import UnlockDeploymentRequest +from .types.config import UpdateDeploymentRequest +from .types.config import QuotaValidation + +__all__ = ( + 'ConfigAsyncClient', +'ApplyResults', +'ConfigClient', +'CreateDeploymentRequest', +'CreatePreviewRequest', +'DeleteDeploymentRequest', +'DeletePreviewRequest', +'DeleteStatefileRequest', +'Deployment', +'DeploymentOperationMetadata', +'ExportDeploymentStatefileRequest', +'ExportLockInfoRequest', +'ExportPreviewResultRequest', +'ExportPreviewResultResponse', +'ExportRevisionStatefileRequest', +'GetDeploymentRequest', +'GetPreviewRequest', +'GetResourceChangeRequest', +'GetResourceDriftRequest', +'GetResourceRequest', +'GetRevisionRequest', +'GetTerraformVersionRequest', +'GitSource', +'ImportStatefileRequest', +'ListDeploymentsRequest', +'ListDeploymentsResponse', +'ListPreviewsRequest', +'ListPreviewsResponse', +'ListResourceChangesRequest', +'ListResourceChangesResponse', +'ListResourceDriftsRequest', +'ListResourceDriftsResponse', +'ListResourcesRequest', +'ListResourcesResponse', +'ListRevisionsRequest', +'ListRevisionsResponse', +'ListTerraformVersionsRequest', +'ListTerraformVersionsResponse', +'LockDeploymentRequest', +'LockInfo', +'OperationMetadata', +'Preview', +'PreviewArtifacts', +'PreviewOperationMetadata', +'PreviewResult', +'PropertyChange', +'PropertyDrift', +'ProviderConfig', +'QuotaValidation', +'Resource', +'ResourceCAIInfo', +'ResourceChange', +'ResourceChangeTerraformInfo', +'ResourceDrift', +'ResourceDriftTerraformInfo', +'ResourceTerraformInfo', +'Revision', +'Statefile', +'TerraformBlueprint', +'TerraformError', +'TerraformOutput', +'TerraformVariable', +'TerraformVersion', +'UnlockDeploymentRequest', +'UpdateDeploymentRequest', +) diff --git a/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/gapic_metadata.json b/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/gapic_metadata.json new file mode 100644 index 000000000000..fd2c8bc6dd14 --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/gapic_metadata.json @@ -0,0 +1,433 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.config_v1", + "protoPackage": "google.cloud.config.v1", + "schema": "1.0", + "services": { + "Config": { + "clients": { + "grpc": { + "libraryClient": "ConfigClient", + "rpcs": { + "CreateDeployment": { + "methods": [ + "create_deployment" + ] + }, + "CreatePreview": { + "methods": [ + "create_preview" + ] + }, + "DeleteDeployment": { + "methods": [ + "delete_deployment" + ] + }, + "DeletePreview": { + "methods": [ + "delete_preview" + ] + }, + "DeleteStatefile": { + "methods": [ + "delete_statefile" + ] + }, + "ExportDeploymentStatefile": { + "methods": [ + "export_deployment_statefile" + ] + }, + "ExportLockInfo": { + "methods": [ + "export_lock_info" + ] + }, + "ExportPreviewResult": { + "methods": [ + "export_preview_result" + ] + }, + "ExportRevisionStatefile": { + "methods": [ + "export_revision_statefile" + ] + }, + "GetDeployment": { + "methods": [ + "get_deployment" + ] + }, + "GetPreview": { + "methods": [ + "get_preview" + ] + }, + "GetResource": { + "methods": [ + "get_resource" + ] + }, + "GetResourceChange": { + "methods": [ + "get_resource_change" + ] + }, + "GetResourceDrift": { + "methods": [ + "get_resource_drift" + ] + }, + "GetRevision": { + "methods": [ + "get_revision" + ] + }, + "GetTerraformVersion": { + "methods": [ + "get_terraform_version" + ] + }, + "ImportStatefile": { + "methods": [ + "import_statefile" + ] + }, + "ListDeployments": { + "methods": [ + "list_deployments" + ] + }, + "ListPreviews": { + "methods": [ + "list_previews" + ] + }, + "ListResourceChanges": { + "methods": [ + "list_resource_changes" + ] + }, + "ListResourceDrifts": { + "methods": [ + "list_resource_drifts" + ] + }, + "ListResources": { + "methods": [ + "list_resources" + ] + }, + "ListRevisions": { + "methods": [ + "list_revisions" + ] + }, + "ListTerraformVersions": { + "methods": [ + "list_terraform_versions" + ] + }, + "LockDeployment": { + "methods": [ + "lock_deployment" + ] + }, + "UnlockDeployment": { + "methods": [ + "unlock_deployment" + ] + }, + "UpdateDeployment": { + "methods": [ + "update_deployment" + ] + } + } + }, + "grpc-async": { + "libraryClient": "ConfigAsyncClient", + "rpcs": { + "CreateDeployment": { + "methods": [ + "create_deployment" + ] + }, + "CreatePreview": { + "methods": [ + "create_preview" + ] + }, + "DeleteDeployment": { + "methods": [ + "delete_deployment" + ] + }, + "DeletePreview": { + "methods": [ + "delete_preview" + ] + }, + "DeleteStatefile": { + "methods": [ + "delete_statefile" + ] + }, + "ExportDeploymentStatefile": { + "methods": [ + "export_deployment_statefile" + ] + }, + "ExportLockInfo": { + "methods": [ + "export_lock_info" + ] + }, + "ExportPreviewResult": { + "methods": [ + "export_preview_result" + ] + }, + "ExportRevisionStatefile": { + "methods": [ + "export_revision_statefile" + ] + }, + "GetDeployment": { + "methods": [ + "get_deployment" + ] + }, + "GetPreview": { + "methods": [ + "get_preview" + ] + }, + "GetResource": { + "methods": [ + "get_resource" + ] + }, + "GetResourceChange": { + "methods": [ + "get_resource_change" + ] + }, + "GetResourceDrift": { + "methods": [ + "get_resource_drift" + ] + }, + "GetRevision": { + "methods": [ + "get_revision" + ] + }, + "GetTerraformVersion": { + "methods": [ + "get_terraform_version" + ] + }, + "ImportStatefile": { + "methods": [ + "import_statefile" + ] + }, + "ListDeployments": { + "methods": [ + "list_deployments" + ] + }, + "ListPreviews": { + "methods": [ + "list_previews" + ] + }, + "ListResourceChanges": { + "methods": [ + "list_resource_changes" + ] + }, + "ListResourceDrifts": { + "methods": [ + "list_resource_drifts" + ] + }, + "ListResources": { + "methods": [ + "list_resources" + ] + }, + "ListRevisions": { + "methods": [ + "list_revisions" + ] + }, + "ListTerraformVersions": { + "methods": [ + "list_terraform_versions" + ] + }, + "LockDeployment": { + "methods": [ + "lock_deployment" + ] + }, + "UnlockDeployment": { + "methods": [ + "unlock_deployment" + ] + }, + "UpdateDeployment": { + "methods": [ + "update_deployment" + ] + } + } + }, + "rest": { + "libraryClient": "ConfigClient", + "rpcs": { + "CreateDeployment": { + "methods": [ + "create_deployment" + ] + }, + "CreatePreview": { + "methods": [ + "create_preview" + ] + }, + "DeleteDeployment": { + "methods": [ + "delete_deployment" + ] + }, + "DeletePreview": { + "methods": [ + "delete_preview" + ] + }, + "DeleteStatefile": { + "methods": [ + "delete_statefile" + ] + }, + "ExportDeploymentStatefile": { + "methods": [ + "export_deployment_statefile" + ] + }, + "ExportLockInfo": { + "methods": [ + "export_lock_info" + ] + }, + "ExportPreviewResult": { + "methods": [ + "export_preview_result" + ] + }, + "ExportRevisionStatefile": { + "methods": [ + "export_revision_statefile" + ] + }, + "GetDeployment": { + "methods": [ + "get_deployment" + ] + }, + "GetPreview": { + "methods": [ + "get_preview" + ] + }, + "GetResource": { + "methods": [ + "get_resource" + ] + }, + "GetResourceChange": { + "methods": [ + "get_resource_change" + ] + }, + "GetResourceDrift": { + "methods": [ + "get_resource_drift" + ] + }, + "GetRevision": { + "methods": [ + "get_revision" + ] + }, + "GetTerraformVersion": { + "methods": [ + "get_terraform_version" + ] + }, + "ImportStatefile": { + "methods": [ + "import_statefile" + ] + }, + "ListDeployments": { + "methods": [ + "list_deployments" + ] + }, + "ListPreviews": { + "methods": [ + "list_previews" + ] + }, + "ListResourceChanges": { + "methods": [ + "list_resource_changes" + ] + }, + "ListResourceDrifts": { + "methods": [ + "list_resource_drifts" + ] + }, + "ListResources": { + "methods": [ + "list_resources" + ] + }, + "ListRevisions": { + "methods": [ + "list_revisions" + ] + }, + "ListTerraformVersions": { + "methods": [ + "list_terraform_versions" + ] + }, + "LockDeployment": { + "methods": [ + "lock_deployment" + ] + }, + "UnlockDeployment": { + "methods": [ + "unlock_deployment" + ] + }, + "UpdateDeployment": { + "methods": [ + "update_deployment" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/gapic_version.py b/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/gapic_version.py new file mode 100644 index 000000000000..20a9cd975b02 --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/gapic_version.py @@ -0,0 +1,16 @@ +# -*- 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. +# +__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/py.typed b/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/py.typed new file mode 100644 index 000000000000..f4fe63d2606c --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-config package uses inline types. diff --git a/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/__init__.py b/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/__init__.py new file mode 100644 index 000000000000..cbf94b283c70 --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/__init__.py @@ -0,0 +1,15 @@ +# -*- 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. +# diff --git a/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/__init__.py b/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/__init__.py new file mode 100644 index 000000000000..1b691a8b10de --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/__init__.py @@ -0,0 +1,22 @@ +# -*- 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. +# +from .client import ConfigClient +from .async_client import ConfigAsyncClient + +__all__ = ( + 'ConfigClient', + 'ConfigAsyncClient', +) diff --git a/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/async_client.py b/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/async_client.py new file mode 100644 index 000000000000..d4fe64005767 --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/async_client.py @@ -0,0 +1,4004 @@ +# -*- 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. +# +import logging as std_logging +from collections import OrderedDict +import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.config_v1 import gapic_version as package_version + +from google.api_core.client_options import ClientOptions +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.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore +import google.protobuf + + +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.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.config_v1.services.config import pagers +from google.cloud.config_v1.types import config +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +from .transports.base import ConfigTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import ConfigGrpcAsyncIOTransport +from .client import ConfigClient + +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 ConfigAsyncClient: + """Infrastructure Manager is a managed service that automates + the deployment and management of Google Cloud infrastructure + resources. + """ + + _client: ConfigClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = ConfigClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = ConfigClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = ConfigClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = ConfigClient._DEFAULT_UNIVERSE + + deployment_path = staticmethod(ConfigClient.deployment_path) + parse_deployment_path = staticmethod(ConfigClient.parse_deployment_path) + preview_path = staticmethod(ConfigClient.preview_path) + parse_preview_path = staticmethod(ConfigClient.parse_preview_path) + resource_path = staticmethod(ConfigClient.resource_path) + parse_resource_path = staticmethod(ConfigClient.parse_resource_path) + resource_change_path = staticmethod(ConfigClient.resource_change_path) + parse_resource_change_path = staticmethod(ConfigClient.parse_resource_change_path) + resource_drift_path = staticmethod(ConfigClient.resource_drift_path) + parse_resource_drift_path = staticmethod(ConfigClient.parse_resource_drift_path) + revision_path = staticmethod(ConfigClient.revision_path) + parse_revision_path = staticmethod(ConfigClient.parse_revision_path) + service_account_path = staticmethod(ConfigClient.service_account_path) + parse_service_account_path = staticmethod(ConfigClient.parse_service_account_path) + terraform_version_path = staticmethod(ConfigClient.terraform_version_path) + parse_terraform_version_path = staticmethod(ConfigClient.parse_terraform_version_path) + worker_pool_path = staticmethod(ConfigClient.worker_pool_path) + parse_worker_pool_path = staticmethod(ConfigClient.parse_worker_pool_path) + common_billing_account_path = staticmethod(ConfigClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(ConfigClient.parse_common_billing_account_path) + common_folder_path = staticmethod(ConfigClient.common_folder_path) + parse_common_folder_path = staticmethod(ConfigClient.parse_common_folder_path) + common_organization_path = staticmethod(ConfigClient.common_organization_path) + parse_common_organization_path = staticmethod(ConfigClient.parse_common_organization_path) + common_project_path = staticmethod(ConfigClient.common_project_path) + parse_common_project_path = staticmethod(ConfigClient.parse_common_project_path) + common_location_path = staticmethod(ConfigClient.common_location_path) + parse_common_location_path = staticmethod(ConfigClient.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: + ConfigAsyncClient: The constructed client. + """ + return ConfigClient.from_service_account_info.__func__(ConfigAsyncClient, info, *args, **kwargs) # type: ignore + + @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: + ConfigAsyncClient: The constructed client. + """ + return ConfigClient.from_service_account_file.__func__(ConfigAsyncClient, filename, *args, **kwargs) # type: ignore + + 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 ConfigClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> ConfigTransport: + """Returns the transport used by the client instance. + + Returns: + ConfigTransport: The transport used by the client instance. + """ + return self._client.transport + + @property + def api_endpoint(self): + """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 = ConfigClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, ConfigTransport, Callable[..., ConfigTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the config 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,ConfigTransport,Callable[..., ConfigTransport]]]): + 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 ConfigTransport 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 = ConfigClient( + 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.config_v1.ConfigAsyncClient`.", + extra = { + "serviceName": "google.cloud.config.v1.Config", + "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.config.v1.Config", + "credentialsType": None, + } + ) + + async def list_deployments(self, + request: Optional[Union[config.ListDeploymentsRequest, 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.ListDeploymentsAsyncPager: + r"""Lists [Deployment][google.cloud.config.v1.Deployment]s 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 config_v1 + + async def sample_list_deployments(): + # Create a client + client = config_v1.ConfigAsyncClient() + + # Initialize request argument(s) + request = config_v1.ListDeploymentsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_deployments(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.config_v1.types.ListDeploymentsRequest, dict]]): + The request object. + parent (:class:`str`): + Required. The parent in whose context the Deployments + are listed. The parent value is in the format: + 'projects/{project_id}/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.config_v1.services.config.pagers.ListDeploymentsAsyncPager: + 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, config.ListDeploymentsRequest): + request = config.ListDeploymentsRequest(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_deployments] + + # 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.ListDeploymentsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_deployment(self, + request: Optional[Union[config.GetDeploymentRequest, 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]]] = (), + ) -> config.Deployment: + r"""Gets details about a + [Deployment][google.cloud.config.v1.Deployment]. + + .. 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 config_v1 + + async def sample_get_deployment(): + # Create a client + client = config_v1.ConfigAsyncClient() + + # Initialize request argument(s) + request = config_v1.GetDeploymentRequest( + name="name_value", + ) + + # Make the request + response = await client.get_deployment(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.config_v1.types.GetDeploymentRequest, dict]]): + The request object. + name (:class:`str`): + Required. The name of the deployment. Format: + 'projects/{project_id}/locations/{location}/deployments/{deployment}'. + + 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.config_v1.types.Deployment: + A Deployment is a group of resources + and configs managed and provisioned by + Infra Manager. + + """ + # 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, config.GetDeploymentRequest): + request = config.GetDeploymentRequest(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_deployment] + + # 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_deployment(self, + request: Optional[Union[config.CreateDeploymentRequest, dict]] = None, + *, + parent: Optional[str] = None, + deployment: Optional[config.Deployment] = None, + deployment_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 [Deployment][google.cloud.config.v1.Deployment]. + + .. 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 config_v1 + + async def sample_create_deployment(): + # Create a client + client = config_v1.ConfigAsyncClient() + + # Initialize request argument(s) + deployment = config_v1.Deployment() + deployment.terraform_blueprint.gcs_source = "gcs_source_value" + + request = config_v1.CreateDeploymentRequest( + parent="parent_value", + deployment_id="deployment_id_value", + deployment=deployment, + ) + + # Make the request + operation = client.create_deployment(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.config_v1.types.CreateDeploymentRequest, dict]]): + The request object. + parent (:class:`str`): + Required. The parent in whose context the Deployment is + created. The parent value is in the format: + 'projects/{project_id}/locations/{location}'. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + deployment (:class:`google.cloud.config_v1.types.Deployment`): + Required. + [Deployment][google.cloud.config.v1.Deployment] resource + to be created. + + This corresponds to the ``deployment`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + deployment_id (:class:`str`): + Required. The Deployment ID. + This corresponds to the ``deployment_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.config_v1.types.Deployment` A Deployment is a group of resources and configs managed and provisioned by + Infra Manager. + + """ + # 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, deployment, deployment_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, config.CreateDeploymentRequest): + request = config.CreateDeploymentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if deployment is not None: + request.deployment = deployment + if deployment_id is not None: + request.deployment_id = deployment_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_deployment] + + # 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, + config.Deployment, + metadata_type=config.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_deployment(self, + request: Optional[Union[config.UpdateDeploymentRequest, dict]] = None, + *, + deployment: Optional[config.Deployment] = 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 a [Deployment][google.cloud.config.v1.Deployment]. + + .. 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 config_v1 + + async def sample_update_deployment(): + # Create a client + client = config_v1.ConfigAsyncClient() + + # Initialize request argument(s) + deployment = config_v1.Deployment() + deployment.terraform_blueprint.gcs_source = "gcs_source_value" + + request = config_v1.UpdateDeploymentRequest( + deployment=deployment, + ) + + # Make the request + operation = client.update_deployment(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.config_v1.types.UpdateDeploymentRequest, dict]]): + The request object. + deployment (:class:`google.cloud.config_v1.types.Deployment`): + Required. + [Deployment][google.cloud.config.v1.Deployment] to + update. + + The deployment's ``name`` field is used to identify the + resource to be updated. Format: + ``projects/{project}/locations/{location}/deployments/{deployment}`` + + This corresponds to the ``deployment`` 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 + overwritten in the Deployment 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.config_v1.types.Deployment` A Deployment is a group of resources and configs managed and provisioned by + Infra Manager. + + """ + # 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 = [deployment, 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, config.UpdateDeploymentRequest): + request = config.UpdateDeploymentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if deployment is not None: + request.deployment = deployment + 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_deployment] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("deployment.name", request.deployment.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, + config.Deployment, + metadata_type=config.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_deployment(self, + request: Optional[Union[config.DeleteDeploymentRequest, 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 [Deployment][google.cloud.config.v1.Deployment]. + + .. 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 config_v1 + + async def sample_delete_deployment(): + # Create a client + client = config_v1.ConfigAsyncClient() + + # Initialize request argument(s) + request = config_v1.DeleteDeploymentRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_deployment(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.config_v1.types.DeleteDeploymentRequest, dict]]): + The request object. + name (:class:`str`): + Required. The name of the Deployment in the format: + 'projects/{project_id}/locations/{location}/deployments/{deployment}'. + + 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.config_v1.types.Deployment` A Deployment is a group of resources and configs managed and provisioned by + Infra Manager. + + """ + # 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, config.DeleteDeploymentRequest): + request = config.DeleteDeploymentRequest(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_deployment] + + # 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, + config.Deployment, + metadata_type=config.OperationMetadata, + ) + + # Done; return the response. + return response + + async def list_revisions(self, + request: Optional[Union[config.ListRevisionsRequest, 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.ListRevisionsAsyncPager: + r"""Lists [Revision][google.cloud.config.v1.Revision]s of a + deployment. + + .. 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 config_v1 + + async def sample_list_revisions(): + # Create a client + client = config_v1.ConfigAsyncClient() + + # Initialize request argument(s) + request = config_v1.ListRevisionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_revisions(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.config_v1.types.ListRevisionsRequest, dict]]): + The request object. A request to list Revisions passed to + a 'ListRevisions' call. + parent (:class:`str`): + Required. The parent in whose context the Revisions are + listed. The parent value is in the format: + 'projects/{project_id}/locations/{location}/deployments/{deployment}'. + + 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.config_v1.services.config.pagers.ListRevisionsAsyncPager: + A response to a 'ListRevisions' call. + Contains a list of Revisions. + 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, config.ListRevisionsRequest): + request = config.ListRevisionsRequest(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_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.ListRevisionsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_revision(self, + request: Optional[Union[config.GetRevisionRequest, 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]]] = (), + ) -> config.Revision: + r"""Gets details about a + [Revision][google.cloud.config.v1.Revision]. + + .. 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 config_v1 + + async def sample_get_revision(): + # Create a client + client = config_v1.ConfigAsyncClient() + + # Initialize request argument(s) + request = config_v1.GetRevisionRequest( + name="name_value", + ) + + # Make the request + response = await client.get_revision(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.config_v1.types.GetRevisionRequest, dict]]): + The request object. A request to get a Revision from a + 'GetRevision' call. + name (:class:`str`): + Required. The name of the Revision in the format: + 'projects/{project_id}/locations/{location}/deployments/{deployment}/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.config_v1.types.Revision: + A child resource of a Deployment + generated by a 'CreateDeployment' or + 'UpdateDeployment' call. Each Revision + contains metadata pertaining to a + snapshot of a particular Deployment. + + """ + # 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, config.GetRevisionRequest): + request = config.GetRevisionRequest(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_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 get_resource(self, + request: Optional[Union[config.GetResourceRequest, 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]]] = (), + ) -> config.Resource: + r"""Gets details about a [Resource][google.cloud.config.v1.Resource] + deployed by Infra Manager. + + .. 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 config_v1 + + async def sample_get_resource(): + # Create a client + client = config_v1.ConfigAsyncClient() + + # Initialize request argument(s) + request = config_v1.GetResourceRequest( + name="name_value", + ) + + # Make the request + response = await client.get_resource(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.config_v1.types.GetResourceRequest, dict]]): + The request object. A request to get a Resource from a + 'GetResource' call. + name (:class:`str`): + Required. The name of the Resource in the format: + 'projects/{project_id}/locations/{location}/deployments/{deployment}/revisions/{revision}/resource/{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.config_v1.types.Resource: + Resource represents a Google Cloud + Platform resource actuated by IM. + Resources are child resources of + Revisions. + + """ + # 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, config.GetResourceRequest): + request = config.GetResourceRequest(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_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_resources(self, + request: Optional[Union[config.ListResourcesRequest, 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.ListResourcesAsyncPager: + r"""Lists [Resources][google.cloud.config.v1.Resource] in a given + revision. + + .. 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 config_v1 + + async def sample_list_resources(): + # Create a client + client = config_v1.ConfigAsyncClient() + + # Initialize request argument(s) + request = config_v1.ListResourcesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_resources(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.config_v1.types.ListResourcesRequest, dict]]): + The request object. A request to list Resources passed to + a 'ListResources' call. + parent (:class:`str`): + Required. The parent in whose context the Resources are + listed. The parent value is in the format: + 'projects/{project_id}/locations/{location}/deployments/{deployment}/revisions/{revision}'. + + 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.config_v1.services.config.pagers.ListResourcesAsyncPager: + A response to a 'ListResources' call. + Contains a list of 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, config.ListResourcesRequest): + request = config.ListResourcesRequest(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_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.ListResourcesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def export_deployment_statefile(self, + request: Optional[Union[config.ExportDeploymentStatefileRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> config.Statefile: + r"""Exports Terraform state file from a given deployment. + + .. 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 config_v1 + + async def sample_export_deployment_statefile(): + # Create a client + client = config_v1.ConfigAsyncClient() + + # Initialize request argument(s) + request = config_v1.ExportDeploymentStatefileRequest( + parent="parent_value", + ) + + # Make the request + response = await client.export_deployment_statefile(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.config_v1.types.ExportDeploymentStatefileRequest, dict]]): + The request object. A request to export a state file + passed to a 'ExportDeploymentStatefile' + call. + 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.config_v1.types.Statefile: + Contains info about a Terraform state + file + + """ + # 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, config.ExportDeploymentStatefileRequest): + request = config.ExportDeploymentStatefileRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.export_deployment_statefile] + + # 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 export_revision_statefile(self, + request: Optional[Union[config.ExportRevisionStatefileRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> config.Statefile: + r"""Exports Terraform state file from a given revision. + + .. 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 config_v1 + + async def sample_export_revision_statefile(): + # Create a client + client = config_v1.ConfigAsyncClient() + + # Initialize request argument(s) + request = config_v1.ExportRevisionStatefileRequest( + parent="parent_value", + ) + + # Make the request + response = await client.export_revision_statefile(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.config_v1.types.ExportRevisionStatefileRequest, dict]]): + The request object. A request to export a state file + passed to a 'ExportRevisionStatefile' + call. + 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.config_v1.types.Statefile: + Contains info about a Terraform state + file + + """ + # 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, config.ExportRevisionStatefileRequest): + request = config.ExportRevisionStatefileRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.export_revision_statefile] + + # 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 import_statefile(self, + request: Optional[Union[config.ImportStatefileRequest, dict]] = None, + *, + parent: Optional[str] = None, + lock_id: Optional[int] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> config.Statefile: + r"""Imports Terraform state file in a given deployment. + The state file does not take effect until the Deployment + has been unlocked. + + .. 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 config_v1 + + async def sample_import_statefile(): + # Create a client + client = config_v1.ConfigAsyncClient() + + # Initialize request argument(s) + request = config_v1.ImportStatefileRequest( + parent="parent_value", + lock_id=725, + ) + + # Make the request + response = await client.import_statefile(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.config_v1.types.ImportStatefileRequest, dict]]): + The request object. A request to import a state file + passed to a 'ImportStatefile' call. + parent (:class:`str`): + Required. The parent in whose context the statefile is + listed. The parent value is in the format: + 'projects/{project_id}/locations/{location}/deployments/{deployment}'. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + lock_id (:class:`int`): + Required. Lock ID of the lock file to + verify that the user who is importing + the state file previously locked the + Deployment. + + This corresponds to the ``lock_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.config_v1.types.Statefile: + Contains info about a Terraform state + file + + """ + # 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, lock_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, config.ImportStatefileRequest): + request = config.ImportStatefileRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if lock_id is not None: + request.lock_id = lock_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.import_statefile] + + # 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 delete_statefile(self, + request: Optional[Union[config.DeleteStatefileRequest, 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 Terraform state file in a given deployment. + + .. 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 config_v1 + + async def sample_delete_statefile(): + # Create a client + client = config_v1.ConfigAsyncClient() + + # Initialize request argument(s) + request = config_v1.DeleteStatefileRequest( + name="name_value", + lock_id=725, + ) + + # Make the request + await client.delete_statefile(request=request) + + Args: + request (Optional[Union[google.cloud.config_v1.types.DeleteStatefileRequest, dict]]): + The request object. A request to delete a state file + passed to a 'DeleteStatefile' call. + name (:class:`str`): + Required. The name of the deployment in the format: + 'projects/{project_id}/locations/{location}/deployments/{deployment}'. + + 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, config.DeleteStatefileRequest): + request = config.DeleteStatefileRequest(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_statefile] + + # 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 lock_deployment(self, + request: Optional[Union[config.LockDeploymentRequest, 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"""Locks a deployment. + + .. 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 config_v1 + + async def sample_lock_deployment(): + # Create a client + client = config_v1.ConfigAsyncClient() + + # Initialize request argument(s) + request = config_v1.LockDeploymentRequest( + name="name_value", + ) + + # Make the request + operation = client.lock_deployment(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.config_v1.types.LockDeploymentRequest, dict]]): + The request object. A request to lock a deployment passed + to a 'LockDeployment' call. + name (:class:`str`): + Required. The name of the deployment in the format: + 'projects/{project_id}/locations/{location}/deployments/{deployment}'. + + 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.config_v1.types.Deployment` A Deployment is a group of resources and configs managed and provisioned by + Infra Manager. + + """ + # 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, config.LockDeploymentRequest): + request = config.LockDeploymentRequest(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.lock_deployment] + + # 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, + config.Deployment, + metadata_type=config.OperationMetadata, + ) + + # Done; return the response. + return response + + async def unlock_deployment(self, + request: Optional[Union[config.UnlockDeploymentRequest, dict]] = None, + *, + name: Optional[str] = None, + lock_id: Optional[int] = 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"""Unlocks a locked deployment. + + .. 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 config_v1 + + async def sample_unlock_deployment(): + # Create a client + client = config_v1.ConfigAsyncClient() + + # Initialize request argument(s) + request = config_v1.UnlockDeploymentRequest( + name="name_value", + lock_id=725, + ) + + # Make the request + operation = client.unlock_deployment(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.config_v1.types.UnlockDeploymentRequest, dict]]): + The request object. A request to unlock a state file + passed to a 'UnlockDeployment' call. + name (:class:`str`): + Required. The name of the deployment in the format: + 'projects/{project_id}/locations/{location}/deployments/{deployment}'. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + lock_id (:class:`int`): + Required. Lock ID of the lock file to + be unlocked. + + This corresponds to the ``lock_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.config_v1.types.Deployment` A Deployment is a group of resources and configs managed and provisioned by + Infra Manager. + + """ + # 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, lock_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, config.UnlockDeploymentRequest): + request = config.UnlockDeploymentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if lock_id is not None: + request.lock_id = lock_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.unlock_deployment] + + # 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, + config.Deployment, + metadata_type=config.OperationMetadata, + ) + + # Done; return the response. + return response + + async def export_lock_info(self, + request: Optional[Union[config.ExportLockInfoRequest, 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]]] = (), + ) -> config.LockInfo: + r"""Exports the lock info on a locked deployment. + + .. 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 config_v1 + + async def sample_export_lock_info(): + # Create a client + client = config_v1.ConfigAsyncClient() + + # Initialize request argument(s) + request = config_v1.ExportLockInfoRequest( + name="name_value", + ) + + # Make the request + response = await client.export_lock_info(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.config_v1.types.ExportLockInfoRequest, dict]]): + The request object. A request to get a state file lock + info passed to a 'ExportLockInfo' call. + name (:class:`str`): + Required. The name of the deployment in the format: + 'projects/{project_id}/locations/{location}/deployments/{deployment}'. + + 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.config_v1.types.LockInfo: + Details about the lock which locked + the deployment. + + """ + # 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, config.ExportLockInfoRequest): + request = config.ExportLockInfoRequest(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.export_lock_info] + + # 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_preview(self, + request: Optional[Union[config.CreatePreviewRequest, dict]] = None, + *, + parent: Optional[str] = None, + preview: Optional[config.Preview] = 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 [Preview][google.cloud.config.v1.Preview]. + + .. 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 config_v1 + + async def sample_create_preview(): + # Create a client + client = config_v1.ConfigAsyncClient() + + # Initialize request argument(s) + preview = config_v1.Preview() + preview.terraform_blueprint.gcs_source = "gcs_source_value" + preview.service_account = "service_account_value" + + request = config_v1.CreatePreviewRequest( + parent="parent_value", + preview=preview, + ) + + # Make the request + operation = client.create_preview(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.config_v1.types.CreatePreviewRequest, dict]]): + The request object. A request to create a preview. + parent (:class:`str`): + Required. The parent in whose context the Preview is + created. The parent value is in the format: + 'projects/{project_id}/locations/{location}'. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + preview (:class:`google.cloud.config_v1.types.Preview`): + Required. [Preview][google.cloud.config.v1.Preview] + resource to be created. + + This corresponds to the ``preview`` 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.config_v1.types.Preview` A preview represents a set of actions Infra Manager would perform + to move the resources towards the desired state as + specified in the configuration. + + """ + # 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, preview] + 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, config.CreatePreviewRequest): + request = config.CreatePreviewRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if preview is not None: + request.preview = preview + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_preview] + + # 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, + config.Preview, + metadata_type=config.OperationMetadata, + ) + + # Done; return the response. + return response + + async def get_preview(self, + request: Optional[Union[config.GetPreviewRequest, 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]]] = (), + ) -> config.Preview: + r"""Gets details about a [Preview][google.cloud.config.v1.Preview]. + + .. 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 config_v1 + + async def sample_get_preview(): + # Create a client + client = config_v1.ConfigAsyncClient() + + # Initialize request argument(s) + request = config_v1.GetPreviewRequest( + name="name_value", + ) + + # Make the request + response = await client.get_preview(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.config_v1.types.GetPreviewRequest, dict]]): + The request object. A request to get details about a + preview. + name (:class:`str`): + Required. The name of the preview. Format: + 'projects/{project_id}/locations/{location}/previews/{preview}'. + + 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.config_v1.types.Preview: + A preview represents a set of actions + Infra Manager would perform to move the + resources towards the desired state as + specified in the configuration. + + """ + # 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, config.GetPreviewRequest): + request = config.GetPreviewRequest(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_preview] + + # 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_previews(self, + request: Optional[Union[config.ListPreviewsRequest, 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.ListPreviewsAsyncPager: + r"""Lists [Preview][google.cloud.config.v1.Preview]s 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 config_v1 + + async def sample_list_previews(): + # Create a client + client = config_v1.ConfigAsyncClient() + + # Initialize request argument(s) + request = config_v1.ListPreviewsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_previews(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.config_v1.types.ListPreviewsRequest, dict]]): + The request object. A request to list all previews for a + given project and location. + parent (:class:`str`): + Required. The parent in whose context the Previews are + listed. The parent value is in the format: + 'projects/{project_id}/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.config_v1.services.config.pagers.ListPreviewsAsyncPager: + A response to a ListPreviews call. Contains a list of + Previews. + + 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, config.ListPreviewsRequest): + request = config.ListPreviewsRequest(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_previews] + + # 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.ListPreviewsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_preview(self, + request: Optional[Union[config.DeletePreviewRequest, 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 [Preview][google.cloud.config.v1.Preview]. + + .. 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 config_v1 + + async def sample_delete_preview(): + # Create a client + client = config_v1.ConfigAsyncClient() + + # Initialize request argument(s) + request = config_v1.DeletePreviewRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_preview(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.config_v1.types.DeletePreviewRequest, dict]]): + The request object. A request to delete a preview. + name (:class:`str`): + Required. The name of the Preview in the format: + 'projects/{project_id}/locations/{location}/previews/{preview}'. + + 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.config_v1.types.Preview` A preview represents a set of actions Infra Manager would perform + to move the resources towards the desired state as + specified in the configuration. + + """ + # 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, config.DeletePreviewRequest): + request = config.DeletePreviewRequest(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_preview] + + # 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, + config.Preview, + metadata_type=config.OperationMetadata, + ) + + # Done; return the response. + return response + + async def export_preview_result(self, + request: Optional[Union[config.ExportPreviewResultRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> config.ExportPreviewResultResponse: + r"""Export [Preview][google.cloud.config.v1.Preview] results. + + .. 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 config_v1 + + async def sample_export_preview_result(): + # Create a client + client = config_v1.ConfigAsyncClient() + + # Initialize request argument(s) + request = config_v1.ExportPreviewResultRequest( + parent="parent_value", + ) + + # Make the request + response = await client.export_preview_result(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.config_v1.types.ExportPreviewResultRequest, dict]]): + The request object. A request to export preview results. + 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.config_v1.types.ExportPreviewResultResponse: + A response to ExportPreviewResult call. Contains preview + results. + + """ + # 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, config.ExportPreviewResultRequest): + request = config.ExportPreviewResultRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.export_preview_result] + + # 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 list_terraform_versions(self, + request: Optional[Union[config.ListTerraformVersionsRequest, 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.ListTerraformVersionsAsyncPager: + r"""Lists + [TerraformVersion][google.cloud.config.v1.TerraformVersion]s 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 config_v1 + + async def sample_list_terraform_versions(): + # Create a client + client = config_v1.ConfigAsyncClient() + + # Initialize request argument(s) + request = config_v1.ListTerraformVersionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_terraform_versions(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.config_v1.types.ListTerraformVersionsRequest, dict]]): + The request object. The request message for the + ListTerraformVersions method. + parent (:class:`str`): + Required. The parent in whose context the + TerraformVersions are listed. The parent value is in the + format: 'projects/{project_id}/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.config_v1.services.config.pagers.ListTerraformVersionsAsyncPager: + The response message for the ListTerraformVersions + 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, config.ListTerraformVersionsRequest): + request = config.ListTerraformVersionsRequest(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_terraform_versions] + + # 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.ListTerraformVersionsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_terraform_version(self, + request: Optional[Union[config.GetTerraformVersionRequest, 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]]] = (), + ) -> config.TerraformVersion: + r"""Gets details about a + [TerraformVersion][google.cloud.config.v1.TerraformVersion]. + + .. 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 config_v1 + + async def sample_get_terraform_version(): + # Create a client + client = config_v1.ConfigAsyncClient() + + # Initialize request argument(s) + request = config_v1.GetTerraformVersionRequest( + name="name_value", + ) + + # Make the request + response = await client.get_terraform_version(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.config_v1.types.GetTerraformVersionRequest, dict]]): + The request object. The request message for the + GetTerraformVersion method. + name (:class:`str`): + Required. The name of the TerraformVersion. Format: + 'projects/{project_id}/locations/{location}/terraformVersions/{terraform_version}' + + 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.config_v1.types.TerraformVersion: + A TerraformVersion represents the + support state the corresponding + Terraform version. + + """ + # 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, config.GetTerraformVersionRequest): + request = config.GetTerraformVersionRequest(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_terraform_version] + + # 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_resource_changes(self, + request: Optional[Union[config.ListResourceChangesRequest, 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.ListResourceChangesAsyncPager: + r"""Lists ResourceChanges for a given preview. + + .. 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 config_v1 + + async def sample_list_resource_changes(): + # Create a client + client = config_v1.ConfigAsyncClient() + + # Initialize request argument(s) + request = config_v1.ListResourceChangesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_resource_changes(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.config_v1.types.ListResourceChangesRequest, dict]]): + The request object. The request message for the + ListResourceChanges method. + parent (:class:`str`): + Required. The parent in whose context the + ResourceChanges are listed. The parent value is in the + format: + 'projects/{project_id}/locations/{location}/previews/{preview}'. + + 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.config_v1.services.config.pagers.ListResourceChangesAsyncPager: + A response to a 'ListResourceChanges' + call. Contains a list of + ResourceChanges. + + 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, config.ListResourceChangesRequest): + request = config.ListResourceChangesRequest(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_changes] + + # 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.ListResourceChangesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_resource_change(self, + request: Optional[Union[config.GetResourceChangeRequest, 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]]] = (), + ) -> config.ResourceChange: + r"""Get a ResourceChange for a given preview. + + .. 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 config_v1 + + async def sample_get_resource_change(): + # Create a client + client = config_v1.ConfigAsyncClient() + + # Initialize request argument(s) + request = config_v1.GetResourceChangeRequest( + name="name_value", + ) + + # Make the request + response = await client.get_resource_change(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.config_v1.types.GetResourceChangeRequest, dict]]): + The request object. The request message for the + GetResourceChange method. + name (:class:`str`): + Required. The name of the resource change to retrieve. + Format: + 'projects/{project_id}/locations/{location}/previews/{preview}/resourceChanges/{resource_change}'. + + 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.config_v1.types.ResourceChange: + A resource change represents a change + to a resource in the state file. + + """ + # 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, config.GetResourceChangeRequest): + request = config.GetResourceChangeRequest(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_resource_change] + + # 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_resource_drifts(self, + request: Optional[Union[config.ListResourceDriftsRequest, 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.ListResourceDriftsAsyncPager: + r"""List ResourceDrifts for a given preview. + + .. 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 config_v1 + + async def sample_list_resource_drifts(): + # Create a client + client = config_v1.ConfigAsyncClient() + + # Initialize request argument(s) + request = config_v1.ListResourceDriftsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_resource_drifts(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.config_v1.types.ListResourceDriftsRequest, dict]]): + The request object. The request message for the + ListResourceDrifts method. + parent (:class:`str`): + Required. The parent in whose context the ResourceDrifts + are listed. The parent value is in the format: + 'projects/{project_id}/locations/{location}/previews/{preview}'. + + 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.config_v1.services.config.pagers.ListResourceDriftsAsyncPager: + A response to a 'ListResourceDrifts' + call. Contains a list of ResourceDrifts. + 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, config.ListResourceDriftsRequest): + request = config.ListResourceDriftsRequest(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_drifts] + + # 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.ListResourceDriftsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_resource_drift(self, + request: Optional[Union[config.GetResourceDriftRequest, 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]]] = (), + ) -> config.ResourceDrift: + r"""Get a ResourceDrift for a given preview. + + .. 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 config_v1 + + async def sample_get_resource_drift(): + # Create a client + client = config_v1.ConfigAsyncClient() + + # Initialize request argument(s) + request = config_v1.GetResourceDriftRequest( + name="name_value", + ) + + # Make the request + response = await client.get_resource_drift(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.config_v1.types.GetResourceDriftRequest, dict]]): + The request object. The request message for the + GetResourceDrift method. + name (:class:`str`): + Required. The name of the resource drift to retrieve. + Format: + 'projects/{project_id}/locations/{location}/previews/{preview}/resourceDrifts/{resource_drift}'. + + 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.config_v1.types.ResourceDrift: + A resource drift represents a drift + to a resource in the state file. + + """ + # 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, config.GetResourceDriftRequest): + request = config.GetResourceDriftRequest(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_resource_drift] + + # 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_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = 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 isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**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.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_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = 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 isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**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.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 delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = 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 isinstance(request, dict): + request = operations_pb2.DeleteOperationRequest(**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.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + async def cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = 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 isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**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.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + async def set_iam_policy( + self, + request: Optional[iam_policy_pb2.SetIamPolicyRequest] = 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 isinstance(request, dict): + request = iam_policy_pb2.SetIamPolicyRequest(**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.resource),)), + ) + + # 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_iam_policy( + self, + request: Optional[iam_policy_pb2.GetIamPolicyRequest] = 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 isinstance(request, dict): + request = iam_policy_pb2.GetIamPolicyRequest(**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.resource),)), + ) + + # 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 test_iam_permissions( + self, + request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = 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 isinstance(request, dict): + request = iam_policy_pb2.TestIamPermissionsRequest(**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.resource),)), + ) + + # 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_location( + self, + request: Optional[locations_pb2.GetLocationRequest] = 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 isinstance(request, dict): + request = locations_pb2.GetLocationRequest(**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.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_locations( + self, + request: Optional[locations_pb2.ListLocationsRequest] = 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 isinstance(request, dict): + request = locations_pb2.ListLocationsRequest(**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.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 __aenter__(self) -> "ConfigAsyncClient": + 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__) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +__all__ = ( + "ConfigAsyncClient", +) diff --git a/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/client.py b/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/client.py new file mode 100644 index 000000000000..f8d0c7523492 --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/client.py @@ -0,0 +1,4436 @@ +# -*- 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. +# +from collections import OrderedDict +from http import HTTPStatus +import json +import logging as std_logging +import os +import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast +import warnings + +from google.cloud.config_v1 import gapic_version as package_version + +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.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore +import google.protobuf + +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.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.config_v1.services.config import pagers +from google.cloud.config_v1.types import config +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +from .transports.base import ConfigTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import ConfigGrpcTransport +from .transports.grpc_asyncio import ConfigGrpcAsyncIOTransport +from .transports.rest import ConfigRestTransport + + +class ConfigClientMeta(type): + """Metaclass for the Config 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[ConfigTransport]] + _transport_registry["grpc"] = ConfigGrpcTransport + _transport_registry["grpc_asyncio"] = ConfigGrpcAsyncIOTransport + _transport_registry["rest"] = ConfigRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[ConfigTransport]: + """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 ConfigClient(metaclass=ConfigClientMeta): + """Infrastructure Manager is a managed service that automates + the deployment and management of Google Cloud infrastructure + resources. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "config.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "config.{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: + ConfigClient: 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: + ConfigClient: 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) -> ConfigTransport: + """Returns the transport used by the client instance. + + Returns: + ConfigTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def deployment_path(project: str,location: str,deployment: str,) -> str: + """Returns a fully-qualified deployment string.""" + return "projects/{project}/locations/{location}/deployments/{deployment}".format(project=project, location=location, deployment=deployment, ) + + @staticmethod + def parse_deployment_path(path: str) -> Dict[str,str]: + """Parses a deployment path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/deployments/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def preview_path(project: str,location: str,preview: str,) -> str: + """Returns a fully-qualified preview string.""" + return "projects/{project}/locations/{location}/previews/{preview}".format(project=project, location=location, preview=preview, ) + + @staticmethod + def parse_preview_path(path: str) -> Dict[str,str]: + """Parses a preview path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/previews/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def resource_path(project: str,location: str,deployment: str,revision: str,resource: str,) -> str: + """Returns a fully-qualified resource string.""" + return "projects/{project}/locations/{location}/deployments/{deployment}/revisions/{revision}/resources/{resource}".format(project=project, location=location, deployment=deployment, revision=revision, resource=resource, ) + + @staticmethod + def parse_resource_path(path: str) -> Dict[str,str]: + """Parses a resource path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/deployments/(?P.+?)/revisions/(?P.+?)/resources/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def resource_change_path(project: str,location: str,preview: str,resource_change: str,) -> str: + """Returns a fully-qualified resource_change string.""" + return "projects/{project}/locations/{location}/previews/{preview}/resourceChanges/{resource_change}".format(project=project, location=location, preview=preview, resource_change=resource_change, ) + + @staticmethod + def parse_resource_change_path(path: str) -> Dict[str,str]: + """Parses a resource_change path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/previews/(?P.+?)/resourceChanges/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def resource_drift_path(project: str,location: str,preview: str,resource_drift: str,) -> str: + """Returns a fully-qualified resource_drift string.""" + return "projects/{project}/locations/{location}/previews/{preview}/resourceDrifts/{resource_drift}".format(project=project, location=location, preview=preview, resource_drift=resource_drift, ) + + @staticmethod + def parse_resource_drift_path(path: str) -> Dict[str,str]: + """Parses a resource_drift path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/previews/(?P.+?)/resourceDrifts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def revision_path(project: str,location: str,deployment: str,revision: str,) -> str: + """Returns a fully-qualified revision string.""" + return "projects/{project}/locations/{location}/deployments/{deployment}/revisions/{revision}".format(project=project, location=location, deployment=deployment, revision=revision, ) + + @staticmethod + def parse_revision_path(path: str) -> Dict[str,str]: + """Parses a revision path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/deployments/(?P.+?)/revisions/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def service_account_path(project: str,service_account: str,) -> str: + """Returns a fully-qualified service_account string.""" + return "projects/{project}/serviceAccounts/{service_account}".format(project=project, service_account=service_account, ) + + @staticmethod + def parse_service_account_path(path: str) -> Dict[str,str]: + """Parses a service_account path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/serviceAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def terraform_version_path(project: str,location: str,terraform_version: str,) -> str: + """Returns a fully-qualified terraform_version string.""" + return "projects/{project}/locations/{location}/terraformVersions/{terraform_version}".format(project=project, location=location, terraform_version=terraform_version, ) + + @staticmethod + def parse_terraform_version_path(path: str) -> Dict[str,str]: + """Parses a terraform_version path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/terraformVersions/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def worker_pool_path(project: str,location: str,worker_pool: str,) -> str: + """Returns a fully-qualified worker_pool string.""" + return "projects/{project}/locations/{location}/workerPools/{worker_pool}".format(project=project, location=location, worker_pool=worker_pool, ) + + @staticmethod + def parse_worker_pool_path(path: str) -> Dict[str,str]: + """Parses a worker_pool path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/workerPools/(?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 = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + 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 == "true": + 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 + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + 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 = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + 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 == "true", use_mtls_endpoint, universe_domain_env + + @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 + + @staticmethod + def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint): + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + _default_universe = ConfigClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = ConfigClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = ConfigClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=universe_domain) + return api_endpoint + + @staticmethod + def _get_universe_domain(client_universe_domain: Optional[str], universe_domain_env: Optional[str]) -> str: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured via the client options. + universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = ConfigClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + 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): + """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, ConfigTransport, Callable[..., ConfigTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the config 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,ConfigTransport,Callable[..., ConfigTransport]]]): + 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 ConfigTransport 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 = ConfigClient._read_environment_variables() + self._client_cert_source = ConfigClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = ConfigClient._get_universe_domain(universe_domain_opt, self._universe_domain_env) + self._api_endpoint = None # 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, ConfigTransport) + if transport_provided: + # transport is a ConfigTransport 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(ConfigTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + ConfigClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint)) + + 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[ConfigTransport], Callable[..., ConfigTransport]] = ( + ConfigClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., ConfigTransport], 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.config_v1.ConfigClient`.", + extra = { + "serviceName": "google.cloud.config.v1.Config", + "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.config.v1.Config", + "credentialsType": None, + } + ) + + def list_deployments(self, + request: Optional[Union[config.ListDeploymentsRequest, 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.ListDeploymentsPager: + r"""Lists [Deployment][google.cloud.config.v1.Deployment]s 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 config_v1 + + def sample_list_deployments(): + # Create a client + client = config_v1.ConfigClient() + + # Initialize request argument(s) + request = config_v1.ListDeploymentsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_deployments(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.config_v1.types.ListDeploymentsRequest, dict]): + The request object. + parent (str): + Required. The parent in whose context the Deployments + are listed. The parent value is in the format: + 'projects/{project_id}/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.config_v1.services.config.pagers.ListDeploymentsPager: + 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, config.ListDeploymentsRequest): + request = config.ListDeploymentsRequest(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_deployments] + + # 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.ListDeploymentsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_deployment(self, + request: Optional[Union[config.GetDeploymentRequest, 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]]] = (), + ) -> config.Deployment: + r"""Gets details about a + [Deployment][google.cloud.config.v1.Deployment]. + + .. 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 config_v1 + + def sample_get_deployment(): + # Create a client + client = config_v1.ConfigClient() + + # Initialize request argument(s) + request = config_v1.GetDeploymentRequest( + name="name_value", + ) + + # Make the request + response = client.get_deployment(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.config_v1.types.GetDeploymentRequest, dict]): + The request object. + name (str): + Required. The name of the deployment. Format: + 'projects/{project_id}/locations/{location}/deployments/{deployment}'. + + 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.config_v1.types.Deployment: + A Deployment is a group of resources + and configs managed and provisioned by + Infra Manager. + + """ + # 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, config.GetDeploymentRequest): + request = config.GetDeploymentRequest(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_deployment] + + # 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_deployment(self, + request: Optional[Union[config.CreateDeploymentRequest, dict]] = None, + *, + parent: Optional[str] = None, + deployment: Optional[config.Deployment] = None, + deployment_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 [Deployment][google.cloud.config.v1.Deployment]. + + .. 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 config_v1 + + def sample_create_deployment(): + # Create a client + client = config_v1.ConfigClient() + + # Initialize request argument(s) + deployment = config_v1.Deployment() + deployment.terraform_blueprint.gcs_source = "gcs_source_value" + + request = config_v1.CreateDeploymentRequest( + parent="parent_value", + deployment_id="deployment_id_value", + deployment=deployment, + ) + + # Make the request + operation = client.create_deployment(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.config_v1.types.CreateDeploymentRequest, dict]): + The request object. + parent (str): + Required. The parent in whose context the Deployment is + created. The parent value is in the format: + 'projects/{project_id}/locations/{location}'. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + deployment (google.cloud.config_v1.types.Deployment): + Required. + [Deployment][google.cloud.config.v1.Deployment] resource + to be created. + + This corresponds to the ``deployment`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + deployment_id (str): + Required. The Deployment ID. + This corresponds to the ``deployment_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.config_v1.types.Deployment` A Deployment is a group of resources and configs managed and provisioned by + Infra Manager. + + """ + # 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, deployment, deployment_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, config.CreateDeploymentRequest): + request = config.CreateDeploymentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if deployment is not None: + request.deployment = deployment + if deployment_id is not None: + request.deployment_id = deployment_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_deployment] + + # 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, + config.Deployment, + metadata_type=config.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_deployment(self, + request: Optional[Union[config.UpdateDeploymentRequest, dict]] = None, + *, + deployment: Optional[config.Deployment] = 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 a [Deployment][google.cloud.config.v1.Deployment]. + + .. 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 config_v1 + + def sample_update_deployment(): + # Create a client + client = config_v1.ConfigClient() + + # Initialize request argument(s) + deployment = config_v1.Deployment() + deployment.terraform_blueprint.gcs_source = "gcs_source_value" + + request = config_v1.UpdateDeploymentRequest( + deployment=deployment, + ) + + # Make the request + operation = client.update_deployment(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.config_v1.types.UpdateDeploymentRequest, dict]): + The request object. + deployment (google.cloud.config_v1.types.Deployment): + Required. + [Deployment][google.cloud.config.v1.Deployment] to + update. + + The deployment's ``name`` field is used to identify the + resource to be updated. Format: + ``projects/{project}/locations/{location}/deployments/{deployment}`` + + This corresponds to the ``deployment`` 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 + overwritten in the Deployment 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.config_v1.types.Deployment` A Deployment is a group of resources and configs managed and provisioned by + Infra Manager. + + """ + # 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 = [deployment, 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, config.UpdateDeploymentRequest): + request = config.UpdateDeploymentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if deployment is not None: + request.deployment = deployment + 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_deployment] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("deployment.name", request.deployment.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, + config.Deployment, + metadata_type=config.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_deployment(self, + request: Optional[Union[config.DeleteDeploymentRequest, 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 [Deployment][google.cloud.config.v1.Deployment]. + + .. 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 config_v1 + + def sample_delete_deployment(): + # Create a client + client = config_v1.ConfigClient() + + # Initialize request argument(s) + request = config_v1.DeleteDeploymentRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_deployment(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.config_v1.types.DeleteDeploymentRequest, dict]): + The request object. + name (str): + Required. The name of the Deployment in the format: + 'projects/{project_id}/locations/{location}/deployments/{deployment}'. + + 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.config_v1.types.Deployment` A Deployment is a group of resources and configs managed and provisioned by + Infra Manager. + + """ + # 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, config.DeleteDeploymentRequest): + request = config.DeleteDeploymentRequest(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_deployment] + + # 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, + config.Deployment, + metadata_type=config.OperationMetadata, + ) + + # Done; return the response. + return response + + def list_revisions(self, + request: Optional[Union[config.ListRevisionsRequest, 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.ListRevisionsPager: + r"""Lists [Revision][google.cloud.config.v1.Revision]s of a + deployment. + + .. 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 config_v1 + + def sample_list_revisions(): + # Create a client + client = config_v1.ConfigClient() + + # Initialize request argument(s) + request = config_v1.ListRevisionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_revisions(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.config_v1.types.ListRevisionsRequest, dict]): + The request object. A request to list Revisions passed to + a 'ListRevisions' call. + parent (str): + Required. The parent in whose context the Revisions are + listed. The parent value is in the format: + 'projects/{project_id}/locations/{location}/deployments/{deployment}'. + + 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.config_v1.services.config.pagers.ListRevisionsPager: + A response to a 'ListRevisions' call. + Contains a list of Revisions. + 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, config.ListRevisionsRequest): + request = config.ListRevisionsRequest(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_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.ListRevisionsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_revision(self, + request: Optional[Union[config.GetRevisionRequest, 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]]] = (), + ) -> config.Revision: + r"""Gets details about a + [Revision][google.cloud.config.v1.Revision]. + + .. 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 config_v1 + + def sample_get_revision(): + # Create a client + client = config_v1.ConfigClient() + + # Initialize request argument(s) + request = config_v1.GetRevisionRequest( + name="name_value", + ) + + # Make the request + response = client.get_revision(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.config_v1.types.GetRevisionRequest, dict]): + The request object. A request to get a Revision from a + 'GetRevision' call. + name (str): + Required. The name of the Revision in the format: + 'projects/{project_id}/locations/{location}/deployments/{deployment}/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.config_v1.types.Revision: + A child resource of a Deployment + generated by a 'CreateDeployment' or + 'UpdateDeployment' call. Each Revision + contains metadata pertaining to a + snapshot of a particular Deployment. + + """ + # 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, config.GetRevisionRequest): + request = config.GetRevisionRequest(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_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 get_resource(self, + request: Optional[Union[config.GetResourceRequest, 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]]] = (), + ) -> config.Resource: + r"""Gets details about a [Resource][google.cloud.config.v1.Resource] + deployed by Infra Manager. + + .. 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 config_v1 + + def sample_get_resource(): + # Create a client + client = config_v1.ConfigClient() + + # Initialize request argument(s) + request = config_v1.GetResourceRequest( + name="name_value", + ) + + # Make the request + response = client.get_resource(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.config_v1.types.GetResourceRequest, dict]): + The request object. A request to get a Resource from a + 'GetResource' call. + name (str): + Required. The name of the Resource in the format: + 'projects/{project_id}/locations/{location}/deployments/{deployment}/revisions/{revision}/resource/{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.config_v1.types.Resource: + Resource represents a Google Cloud + Platform resource actuated by IM. + Resources are child resources of + Revisions. + + """ + # 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, config.GetResourceRequest): + request = config.GetResourceRequest(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_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_resources(self, + request: Optional[Union[config.ListResourcesRequest, 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.ListResourcesPager: + r"""Lists [Resources][google.cloud.config.v1.Resource] in a given + revision. + + .. 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 config_v1 + + def sample_list_resources(): + # Create a client + client = config_v1.ConfigClient() + + # Initialize request argument(s) + request = config_v1.ListResourcesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_resources(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.config_v1.types.ListResourcesRequest, dict]): + The request object. A request to list Resources passed to + a 'ListResources' call. + parent (str): + Required. The parent in whose context the Resources are + listed. The parent value is in the format: + 'projects/{project_id}/locations/{location}/deployments/{deployment}/revisions/{revision}'. + + 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.config_v1.services.config.pagers.ListResourcesPager: + A response to a 'ListResources' call. + Contains a list of 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, config.ListResourcesRequest): + request = config.ListResourcesRequest(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_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.ListResourcesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def export_deployment_statefile(self, + request: Optional[Union[config.ExportDeploymentStatefileRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> config.Statefile: + r"""Exports Terraform state file from a given deployment. + + .. 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 config_v1 + + def sample_export_deployment_statefile(): + # Create a client + client = config_v1.ConfigClient() + + # Initialize request argument(s) + request = config_v1.ExportDeploymentStatefileRequest( + parent="parent_value", + ) + + # Make the request + response = client.export_deployment_statefile(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.config_v1.types.ExportDeploymentStatefileRequest, dict]): + The request object. A request to export a state file + passed to a 'ExportDeploymentStatefile' + call. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each 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.config_v1.types.Statefile: + Contains info about a Terraform state + file + + """ + # 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, config.ExportDeploymentStatefileRequest): + request = config.ExportDeploymentStatefileRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.export_deployment_statefile] + + # 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 export_revision_statefile(self, + request: Optional[Union[config.ExportRevisionStatefileRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> config.Statefile: + r"""Exports Terraform state file from a given revision. + + .. 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 config_v1 + + def sample_export_revision_statefile(): + # Create a client + client = config_v1.ConfigClient() + + # Initialize request argument(s) + request = config_v1.ExportRevisionStatefileRequest( + parent="parent_value", + ) + + # Make the request + response = client.export_revision_statefile(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.config_v1.types.ExportRevisionStatefileRequest, dict]): + The request object. A request to export a state file + passed to a 'ExportRevisionStatefile' + call. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each 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.config_v1.types.Statefile: + Contains info about a Terraform state + file + + """ + # 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, config.ExportRevisionStatefileRequest): + request = config.ExportRevisionStatefileRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.export_revision_statefile] + + # 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 import_statefile(self, + request: Optional[Union[config.ImportStatefileRequest, dict]] = None, + *, + parent: Optional[str] = None, + lock_id: Optional[int] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> config.Statefile: + r"""Imports Terraform state file in a given deployment. + The state file does not take effect until the Deployment + has been unlocked. + + .. 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 config_v1 + + def sample_import_statefile(): + # Create a client + client = config_v1.ConfigClient() + + # Initialize request argument(s) + request = config_v1.ImportStatefileRequest( + parent="parent_value", + lock_id=725, + ) + + # Make the request + response = client.import_statefile(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.config_v1.types.ImportStatefileRequest, dict]): + The request object. A request to import a state file + passed to a 'ImportStatefile' call. + parent (str): + Required. The parent in whose context the statefile is + listed. The parent value is in the format: + 'projects/{project_id}/locations/{location}/deployments/{deployment}'. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + lock_id (int): + Required. Lock ID of the lock file to + verify that the user who is importing + the state file previously locked the + Deployment. + + This corresponds to the ``lock_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.config_v1.types.Statefile: + Contains info about a Terraform state + file + + """ + # 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, lock_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, config.ImportStatefileRequest): + request = config.ImportStatefileRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if lock_id is not None: + request.lock_id = lock_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.import_statefile] + + # 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 delete_statefile(self, + request: Optional[Union[config.DeleteStatefileRequest, 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 Terraform state file in a given deployment. + + .. 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 config_v1 + + def sample_delete_statefile(): + # Create a client + client = config_v1.ConfigClient() + + # Initialize request argument(s) + request = config_v1.DeleteStatefileRequest( + name="name_value", + lock_id=725, + ) + + # Make the request + client.delete_statefile(request=request) + + Args: + request (Union[google.cloud.config_v1.types.DeleteStatefileRequest, dict]): + The request object. A request to delete a state file + passed to a 'DeleteStatefile' call. + name (str): + Required. The name of the deployment in the format: + 'projects/{project_id}/locations/{location}/deployments/{deployment}'. + + 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, config.DeleteStatefileRequest): + request = config.DeleteStatefileRequest(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_statefile] + + # 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 lock_deployment(self, + request: Optional[Union[config.LockDeploymentRequest, 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"""Locks a deployment. + + .. 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 config_v1 + + def sample_lock_deployment(): + # Create a client + client = config_v1.ConfigClient() + + # Initialize request argument(s) + request = config_v1.LockDeploymentRequest( + name="name_value", + ) + + # Make the request + operation = client.lock_deployment(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.config_v1.types.LockDeploymentRequest, dict]): + The request object. A request to lock a deployment passed + to a 'LockDeployment' call. + name (str): + Required. The name of the deployment in the format: + 'projects/{project_id}/locations/{location}/deployments/{deployment}'. + + 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.config_v1.types.Deployment` A Deployment is a group of resources and configs managed and provisioned by + Infra Manager. + + """ + # 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, config.LockDeploymentRequest): + request = config.LockDeploymentRequest(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.lock_deployment] + + # 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, + config.Deployment, + metadata_type=config.OperationMetadata, + ) + + # Done; return the response. + return response + + def unlock_deployment(self, + request: Optional[Union[config.UnlockDeploymentRequest, dict]] = None, + *, + name: Optional[str] = None, + lock_id: Optional[int] = 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"""Unlocks a locked deployment. + + .. 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 config_v1 + + def sample_unlock_deployment(): + # Create a client + client = config_v1.ConfigClient() + + # Initialize request argument(s) + request = config_v1.UnlockDeploymentRequest( + name="name_value", + lock_id=725, + ) + + # Make the request + operation = client.unlock_deployment(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.config_v1.types.UnlockDeploymentRequest, dict]): + The request object. A request to unlock a state file + passed to a 'UnlockDeployment' call. + name (str): + Required. The name of the deployment in the format: + 'projects/{project_id}/locations/{location}/deployments/{deployment}'. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + lock_id (int): + Required. Lock ID of the lock file to + be unlocked. + + This corresponds to the ``lock_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.config_v1.types.Deployment` A Deployment is a group of resources and configs managed and provisioned by + Infra Manager. + + """ + # 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, lock_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, config.UnlockDeploymentRequest): + request = config.UnlockDeploymentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if lock_id is not None: + request.lock_id = lock_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.unlock_deployment] + + # 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, + config.Deployment, + metadata_type=config.OperationMetadata, + ) + + # Done; return the response. + return response + + def export_lock_info(self, + request: Optional[Union[config.ExportLockInfoRequest, 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]]] = (), + ) -> config.LockInfo: + r"""Exports the lock info on a locked deployment. + + .. 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 config_v1 + + def sample_export_lock_info(): + # Create a client + client = config_v1.ConfigClient() + + # Initialize request argument(s) + request = config_v1.ExportLockInfoRequest( + name="name_value", + ) + + # Make the request + response = client.export_lock_info(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.config_v1.types.ExportLockInfoRequest, dict]): + The request object. A request to get a state file lock + info passed to a 'ExportLockInfo' call. + name (str): + Required. The name of the deployment in the format: + 'projects/{project_id}/locations/{location}/deployments/{deployment}'. + + 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.config_v1.types.LockInfo: + Details about the lock which locked + the deployment. + + """ + # 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, config.ExportLockInfoRequest): + request = config.ExportLockInfoRequest(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.export_lock_info] + + # 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_preview(self, + request: Optional[Union[config.CreatePreviewRequest, dict]] = None, + *, + parent: Optional[str] = None, + preview: Optional[config.Preview] = 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 [Preview][google.cloud.config.v1.Preview]. + + .. 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 config_v1 + + def sample_create_preview(): + # Create a client + client = config_v1.ConfigClient() + + # Initialize request argument(s) + preview = config_v1.Preview() + preview.terraform_blueprint.gcs_source = "gcs_source_value" + preview.service_account = "service_account_value" + + request = config_v1.CreatePreviewRequest( + parent="parent_value", + preview=preview, + ) + + # Make the request + operation = client.create_preview(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.config_v1.types.CreatePreviewRequest, dict]): + The request object. A request to create a preview. + parent (str): + Required. The parent in whose context the Preview is + created. The parent value is in the format: + 'projects/{project_id}/locations/{location}'. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + preview (google.cloud.config_v1.types.Preview): + Required. [Preview][google.cloud.config.v1.Preview] + resource to be created. + + This corresponds to the ``preview`` 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.config_v1.types.Preview` A preview represents a set of actions Infra Manager would perform + to move the resources towards the desired state as + specified in the configuration. + + """ + # 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, preview] + 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, config.CreatePreviewRequest): + request = config.CreatePreviewRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if preview is not None: + request.preview = preview + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_preview] + + # 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, + config.Preview, + metadata_type=config.OperationMetadata, + ) + + # Done; return the response. + return response + + def get_preview(self, + request: Optional[Union[config.GetPreviewRequest, 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]]] = (), + ) -> config.Preview: + r"""Gets details about a [Preview][google.cloud.config.v1.Preview]. + + .. 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 config_v1 + + def sample_get_preview(): + # Create a client + client = config_v1.ConfigClient() + + # Initialize request argument(s) + request = config_v1.GetPreviewRequest( + name="name_value", + ) + + # Make the request + response = client.get_preview(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.config_v1.types.GetPreviewRequest, dict]): + The request object. A request to get details about a + preview. + name (str): + Required. The name of the preview. Format: + 'projects/{project_id}/locations/{location}/previews/{preview}'. + + 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.config_v1.types.Preview: + A preview represents a set of actions + Infra Manager would perform to move the + resources towards the desired state as + specified in the configuration. + + """ + # 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, config.GetPreviewRequest): + request = config.GetPreviewRequest(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_preview] + + # 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_previews(self, + request: Optional[Union[config.ListPreviewsRequest, 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.ListPreviewsPager: + r"""Lists [Preview][google.cloud.config.v1.Preview]s 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 config_v1 + + def sample_list_previews(): + # Create a client + client = config_v1.ConfigClient() + + # Initialize request argument(s) + request = config_v1.ListPreviewsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_previews(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.config_v1.types.ListPreviewsRequest, dict]): + The request object. A request to list all previews for a + given project and location. + parent (str): + Required. The parent in whose context the Previews are + listed. The parent value is in the format: + 'projects/{project_id}/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.config_v1.services.config.pagers.ListPreviewsPager: + A response to a ListPreviews call. Contains a list of + Previews. + + 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, config.ListPreviewsRequest): + request = config.ListPreviewsRequest(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_previews] + + # 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.ListPreviewsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_preview(self, + request: Optional[Union[config.DeletePreviewRequest, 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 [Preview][google.cloud.config.v1.Preview]. + + .. 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 config_v1 + + def sample_delete_preview(): + # Create a client + client = config_v1.ConfigClient() + + # Initialize request argument(s) + request = config_v1.DeletePreviewRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_preview(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.config_v1.types.DeletePreviewRequest, dict]): + The request object. A request to delete a preview. + name (str): + Required. The name of the Preview in the format: + 'projects/{project_id}/locations/{location}/previews/{preview}'. + + 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.config_v1.types.Preview` A preview represents a set of actions Infra Manager would perform + to move the resources towards the desired state as + specified in the configuration. + + """ + # 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, config.DeletePreviewRequest): + request = config.DeletePreviewRequest(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_preview] + + # 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, + config.Preview, + metadata_type=config.OperationMetadata, + ) + + # Done; return the response. + return response + + def export_preview_result(self, + request: Optional[Union[config.ExportPreviewResultRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> config.ExportPreviewResultResponse: + r"""Export [Preview][google.cloud.config.v1.Preview] results. + + .. 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 config_v1 + + def sample_export_preview_result(): + # Create a client + client = config_v1.ConfigClient() + + # Initialize request argument(s) + request = config_v1.ExportPreviewResultRequest( + parent="parent_value", + ) + + # Make the request + response = client.export_preview_result(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.config_v1.types.ExportPreviewResultRequest, dict]): + The request object. A request to export preview results. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each 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.config_v1.types.ExportPreviewResultResponse: + A response to ExportPreviewResult call. Contains preview + results. + + """ + # 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, config.ExportPreviewResultRequest): + request = config.ExportPreviewResultRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.export_preview_result] + + # 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 list_terraform_versions(self, + request: Optional[Union[config.ListTerraformVersionsRequest, 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.ListTerraformVersionsPager: + r"""Lists + [TerraformVersion][google.cloud.config.v1.TerraformVersion]s 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 config_v1 + + def sample_list_terraform_versions(): + # Create a client + client = config_v1.ConfigClient() + + # Initialize request argument(s) + request = config_v1.ListTerraformVersionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_terraform_versions(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.config_v1.types.ListTerraformVersionsRequest, dict]): + The request object. The request message for the + ListTerraformVersions method. + parent (str): + Required. The parent in whose context the + TerraformVersions are listed. The parent value is in the + format: 'projects/{project_id}/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.config_v1.services.config.pagers.ListTerraformVersionsPager: + The response message for the ListTerraformVersions + 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, config.ListTerraformVersionsRequest): + request = config.ListTerraformVersionsRequest(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_terraform_versions] + + # 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.ListTerraformVersionsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_terraform_version(self, + request: Optional[Union[config.GetTerraformVersionRequest, 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]]] = (), + ) -> config.TerraformVersion: + r"""Gets details about a + [TerraformVersion][google.cloud.config.v1.TerraformVersion]. + + .. 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 config_v1 + + def sample_get_terraform_version(): + # Create a client + client = config_v1.ConfigClient() + + # Initialize request argument(s) + request = config_v1.GetTerraformVersionRequest( + name="name_value", + ) + + # Make the request + response = client.get_terraform_version(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.config_v1.types.GetTerraformVersionRequest, dict]): + The request object. The request message for the + GetTerraformVersion method. + name (str): + Required. The name of the TerraformVersion. Format: + 'projects/{project_id}/locations/{location}/terraformVersions/{terraform_version}' + + 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.config_v1.types.TerraformVersion: + A TerraformVersion represents the + support state the corresponding + Terraform version. + + """ + # 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, config.GetTerraformVersionRequest): + request = config.GetTerraformVersionRequest(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_terraform_version] + + # 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_resource_changes(self, + request: Optional[Union[config.ListResourceChangesRequest, 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.ListResourceChangesPager: + r"""Lists ResourceChanges for a given preview. + + .. 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 config_v1 + + def sample_list_resource_changes(): + # Create a client + client = config_v1.ConfigClient() + + # Initialize request argument(s) + request = config_v1.ListResourceChangesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_resource_changes(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.config_v1.types.ListResourceChangesRequest, dict]): + The request object. The request message for the + ListResourceChanges method. + parent (str): + Required. The parent in whose context the + ResourceChanges are listed. The parent value is in the + format: + 'projects/{project_id}/locations/{location}/previews/{preview}'. + + 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.config_v1.services.config.pagers.ListResourceChangesPager: + A response to a 'ListResourceChanges' + call. Contains a list of + ResourceChanges. + + 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, config.ListResourceChangesRequest): + request = config.ListResourceChangesRequest(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_changes] + + # 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.ListResourceChangesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_resource_change(self, + request: Optional[Union[config.GetResourceChangeRequest, 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]]] = (), + ) -> config.ResourceChange: + r"""Get a ResourceChange for a given preview. + + .. 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 config_v1 + + def sample_get_resource_change(): + # Create a client + client = config_v1.ConfigClient() + + # Initialize request argument(s) + request = config_v1.GetResourceChangeRequest( + name="name_value", + ) + + # Make the request + response = client.get_resource_change(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.config_v1.types.GetResourceChangeRequest, dict]): + The request object. The request message for the + GetResourceChange method. + name (str): + Required. The name of the resource change to retrieve. + Format: + 'projects/{project_id}/locations/{location}/previews/{preview}/resourceChanges/{resource_change}'. + + 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.config_v1.types.ResourceChange: + A resource change represents a change + to a resource in the state file. + + """ + # 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, config.GetResourceChangeRequest): + request = config.GetResourceChangeRequest(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_resource_change] + + # 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_resource_drifts(self, + request: Optional[Union[config.ListResourceDriftsRequest, 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.ListResourceDriftsPager: + r"""List ResourceDrifts for a given preview. + + .. 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 config_v1 + + def sample_list_resource_drifts(): + # Create a client + client = config_v1.ConfigClient() + + # Initialize request argument(s) + request = config_v1.ListResourceDriftsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_resource_drifts(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.config_v1.types.ListResourceDriftsRequest, dict]): + The request object. The request message for the + ListResourceDrifts method. + parent (str): + Required. The parent in whose context the ResourceDrifts + are listed. The parent value is in the format: + 'projects/{project_id}/locations/{location}/previews/{preview}'. + + 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.config_v1.services.config.pagers.ListResourceDriftsPager: + A response to a 'ListResourceDrifts' + call. Contains a list of ResourceDrifts. + 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, config.ListResourceDriftsRequest): + request = config.ListResourceDriftsRequest(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_drifts] + + # 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.ListResourceDriftsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_resource_drift(self, + request: Optional[Union[config.GetResourceDriftRequest, 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]]] = (), + ) -> config.ResourceDrift: + r"""Get a ResourceDrift for a given preview. + + .. 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 config_v1 + + def sample_get_resource_drift(): + # Create a client + client = config_v1.ConfigClient() + + # Initialize request argument(s) + request = config_v1.GetResourceDriftRequest( + name="name_value", + ) + + # Make the request + response = client.get_resource_drift(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.config_v1.types.GetResourceDriftRequest, dict]): + The request object. The request message for the + GetResourceDrift method. + name (str): + Required. The name of the resource drift to retrieve. + Format: + 'projects/{project_id}/locations/{location}/previews/{preview}/resourceDrifts/{resource_drift}'. + + 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.config_v1.types.ResourceDrift: + A resource drift represents a drift + to a resource in the state file. + + """ + # 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, config.GetResourceDriftRequest): + request = config.GetResourceDriftRequest(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_resource_drift] + + # 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) -> "ConfigClient": + 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[operations_pb2.ListOperationsRequest] = 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 isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**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.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request, 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[operations_pb2.GetOperationRequest] = 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 isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**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.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request, 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[operations_pb2.DeleteOperationRequest] = 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 isinstance(request, dict): + request = operations_pb2.DeleteOperationRequest(**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.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + def cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = 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 isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**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.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + def set_iam_policy( + self, + request: Optional[iam_policy_pb2.SetIamPolicyRequest] = 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 isinstance(request, dict): + request = iam_policy_pb2.SetIamPolicyRequest(**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.resource),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request, 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[iam_policy_pb2.GetIamPolicyRequest] = 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 isinstance(request, dict): + request = iam_policy_pb2.GetIamPolicyRequest(**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.resource),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request, 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[iam_policy_pb2.TestIamPermissionsRequest] = 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 isinstance(request, dict): + request = iam_policy_pb2.TestIamPermissionsRequest(**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.resource),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request, 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[locations_pb2.GetLocationRequest] = 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 isinstance(request, dict): + request = locations_pb2.GetLocationRequest(**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.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request, 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[locations_pb2.ListLocationsRequest] = 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 isinstance(request, dict): + request = locations_pb2.ListLocationsRequest(**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.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request, 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__) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + +__all__ = ( + "ConfigClient", +) diff --git a/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/pagers.py b/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/pagers.py new file mode 100644 index 000000000000..b455a6d6256c --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/pagers.py @@ -0,0 +1,1000 @@ +# -*- 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. +# +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 +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator, Union +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.config_v1.types import config + + +class ListDeploymentsPager: + """A pager for iterating through ``list_deployments`` requests. + + This class thinly wraps an initial + :class:`google.cloud.config_v1.types.ListDeploymentsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``deployments`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListDeployments`` requests and continue to iterate + through the ``deployments`` field on the + corresponding responses. + + All the usual :class:`google.cloud.config_v1.types.ListDeploymentsResponse` + 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[..., config.ListDeploymentsResponse], + request: config.ListDeploymentsRequest, + response: config.ListDeploymentsResponse, + *, + 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.config_v1.types.ListDeploymentsRequest): + The initial request object. + response (google.cloud.config_v1.types.ListDeploymentsResponse): + 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 = config.ListDeploymentsRequest(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[config.ListDeploymentsResponse]: + 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[config.Deployment]: + for page in self.pages: + yield from page.deployments + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListDeploymentsAsyncPager: + """A pager for iterating through ``list_deployments`` requests. + + This class thinly wraps an initial + :class:`google.cloud.config_v1.types.ListDeploymentsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``deployments`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListDeployments`` requests and continue to iterate + through the ``deployments`` field on the + corresponding responses. + + All the usual :class:`google.cloud.config_v1.types.ListDeploymentsResponse` + 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[config.ListDeploymentsResponse]], + request: config.ListDeploymentsRequest, + response: config.ListDeploymentsResponse, + *, + 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.config_v1.types.ListDeploymentsRequest): + The initial request object. + response (google.cloud.config_v1.types.ListDeploymentsResponse): + 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 = config.ListDeploymentsRequest(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[config.ListDeploymentsResponse]: + 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[config.Deployment]: + async def async_generator(): + async for page in self.pages: + for response in page.deployments: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListRevisionsPager: + """A pager for iterating through ``list_revisions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.config_v1.types.ListRevisionsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``revisions`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListRevisions`` requests and continue to iterate + through the ``revisions`` field on the + corresponding responses. + + All the usual :class:`google.cloud.config_v1.types.ListRevisionsResponse` + 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[..., config.ListRevisionsResponse], + request: config.ListRevisionsRequest, + response: config.ListRevisionsResponse, + *, + 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.config_v1.types.ListRevisionsRequest): + The initial request object. + response (google.cloud.config_v1.types.ListRevisionsResponse): + 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 = config.ListRevisionsRequest(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[config.ListRevisionsResponse]: + 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[config.Revision]: + for page in self.pages: + yield from page.revisions + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListRevisionsAsyncPager: + """A pager for iterating through ``list_revisions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.config_v1.types.ListRevisionsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``revisions`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListRevisions`` requests and continue to iterate + through the ``revisions`` field on the + corresponding responses. + + All the usual :class:`google.cloud.config_v1.types.ListRevisionsResponse` + 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[config.ListRevisionsResponse]], + request: config.ListRevisionsRequest, + response: config.ListRevisionsResponse, + *, + 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.config_v1.types.ListRevisionsRequest): + The initial request object. + response (google.cloud.config_v1.types.ListRevisionsResponse): + 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 = config.ListRevisionsRequest(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[config.ListRevisionsResponse]: + 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[config.Revision]: + async def async_generator(): + async for page in self.pages: + for response in page.revisions: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListResourcesPager: + """A pager for iterating through ``list_resources`` requests. + + This class thinly wraps an initial + :class:`google.cloud.config_v1.types.ListResourcesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``resources`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListResources`` requests and continue to iterate + through the ``resources`` field on the + corresponding responses. + + All the usual :class:`google.cloud.config_v1.types.ListResourcesResponse` + 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[..., config.ListResourcesResponse], + request: config.ListResourcesRequest, + response: config.ListResourcesResponse, + *, + 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.config_v1.types.ListResourcesRequest): + The initial request object. + response (google.cloud.config_v1.types.ListResourcesResponse): + 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 = config.ListResourcesRequest(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[config.ListResourcesResponse]: + 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[config.Resource]: + for page in self.pages: + yield from page.resources + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListResourcesAsyncPager: + """A pager for iterating through ``list_resources`` requests. + + This class thinly wraps an initial + :class:`google.cloud.config_v1.types.ListResourcesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``resources`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListResources`` requests and continue to iterate + through the ``resources`` field on the + corresponding responses. + + All the usual :class:`google.cloud.config_v1.types.ListResourcesResponse` + 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[config.ListResourcesResponse]], + request: config.ListResourcesRequest, + response: config.ListResourcesResponse, + *, + 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.config_v1.types.ListResourcesRequest): + The initial request object. + response (google.cloud.config_v1.types.ListResourcesResponse): + 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 = config.ListResourcesRequest(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[config.ListResourcesResponse]: + 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[config.Resource]: + async def async_generator(): + async for page in self.pages: + for response in page.resources: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListPreviewsPager: + """A pager for iterating through ``list_previews`` requests. + + This class thinly wraps an initial + :class:`google.cloud.config_v1.types.ListPreviewsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``previews`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListPreviews`` requests and continue to iterate + through the ``previews`` field on the + corresponding responses. + + All the usual :class:`google.cloud.config_v1.types.ListPreviewsResponse` + 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[..., config.ListPreviewsResponse], + request: config.ListPreviewsRequest, + response: config.ListPreviewsResponse, + *, + 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.config_v1.types.ListPreviewsRequest): + The initial request object. + response (google.cloud.config_v1.types.ListPreviewsResponse): + 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 = config.ListPreviewsRequest(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[config.ListPreviewsResponse]: + 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[config.Preview]: + for page in self.pages: + yield from page.previews + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListPreviewsAsyncPager: + """A pager for iterating through ``list_previews`` requests. + + This class thinly wraps an initial + :class:`google.cloud.config_v1.types.ListPreviewsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``previews`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListPreviews`` requests and continue to iterate + through the ``previews`` field on the + corresponding responses. + + All the usual :class:`google.cloud.config_v1.types.ListPreviewsResponse` + 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[config.ListPreviewsResponse]], + request: config.ListPreviewsRequest, + response: config.ListPreviewsResponse, + *, + 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.config_v1.types.ListPreviewsRequest): + The initial request object. + response (google.cloud.config_v1.types.ListPreviewsResponse): + 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 = config.ListPreviewsRequest(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[config.ListPreviewsResponse]: + 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[config.Preview]: + async def async_generator(): + async for page in self.pages: + for response in page.previews: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListTerraformVersionsPager: + """A pager for iterating through ``list_terraform_versions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.config_v1.types.ListTerraformVersionsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``terraform_versions`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListTerraformVersions`` requests and continue to iterate + through the ``terraform_versions`` field on the + corresponding responses. + + All the usual :class:`google.cloud.config_v1.types.ListTerraformVersionsResponse` + 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[..., config.ListTerraformVersionsResponse], + request: config.ListTerraformVersionsRequest, + response: config.ListTerraformVersionsResponse, + *, + 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.config_v1.types.ListTerraformVersionsRequest): + The initial request object. + response (google.cloud.config_v1.types.ListTerraformVersionsResponse): + 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 = config.ListTerraformVersionsRequest(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[config.ListTerraformVersionsResponse]: + 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[config.TerraformVersion]: + for page in self.pages: + yield from page.terraform_versions + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListTerraformVersionsAsyncPager: + """A pager for iterating through ``list_terraform_versions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.config_v1.types.ListTerraformVersionsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``terraform_versions`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListTerraformVersions`` requests and continue to iterate + through the ``terraform_versions`` field on the + corresponding responses. + + All the usual :class:`google.cloud.config_v1.types.ListTerraformVersionsResponse` + 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[config.ListTerraformVersionsResponse]], + request: config.ListTerraformVersionsRequest, + response: config.ListTerraformVersionsResponse, + *, + 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.config_v1.types.ListTerraformVersionsRequest): + The initial request object. + response (google.cloud.config_v1.types.ListTerraformVersionsResponse): + 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 = config.ListTerraformVersionsRequest(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[config.ListTerraformVersionsResponse]: + 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[config.TerraformVersion]: + async def async_generator(): + async for page in self.pages: + for response in page.terraform_versions: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListResourceChangesPager: + """A pager for iterating through ``list_resource_changes`` requests. + + This class thinly wraps an initial + :class:`google.cloud.config_v1.types.ListResourceChangesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``resource_changes`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListResourceChanges`` requests and continue to iterate + through the ``resource_changes`` field on the + corresponding responses. + + All the usual :class:`google.cloud.config_v1.types.ListResourceChangesResponse` + 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[..., config.ListResourceChangesResponse], + request: config.ListResourceChangesRequest, + response: config.ListResourceChangesResponse, + *, + 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.config_v1.types.ListResourceChangesRequest): + The initial request object. + response (google.cloud.config_v1.types.ListResourceChangesResponse): + 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 = config.ListResourceChangesRequest(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[config.ListResourceChangesResponse]: + 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[config.ResourceChange]: + for page in self.pages: + yield from page.resource_changes + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListResourceChangesAsyncPager: + """A pager for iterating through ``list_resource_changes`` requests. + + This class thinly wraps an initial + :class:`google.cloud.config_v1.types.ListResourceChangesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``resource_changes`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListResourceChanges`` requests and continue to iterate + through the ``resource_changes`` field on the + corresponding responses. + + All the usual :class:`google.cloud.config_v1.types.ListResourceChangesResponse` + 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[config.ListResourceChangesResponse]], + request: config.ListResourceChangesRequest, + response: config.ListResourceChangesResponse, + *, + 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.config_v1.types.ListResourceChangesRequest): + The initial request object. + response (google.cloud.config_v1.types.ListResourceChangesResponse): + 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 = config.ListResourceChangesRequest(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[config.ListResourceChangesResponse]: + 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[config.ResourceChange]: + async def async_generator(): + async for page in self.pages: + for response in page.resource_changes: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListResourceDriftsPager: + """A pager for iterating through ``list_resource_drifts`` requests. + + This class thinly wraps an initial + :class:`google.cloud.config_v1.types.ListResourceDriftsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``resource_drifts`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListResourceDrifts`` requests and continue to iterate + through the ``resource_drifts`` field on the + corresponding responses. + + All the usual :class:`google.cloud.config_v1.types.ListResourceDriftsResponse` + 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[..., config.ListResourceDriftsResponse], + request: config.ListResourceDriftsRequest, + response: config.ListResourceDriftsResponse, + *, + 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.config_v1.types.ListResourceDriftsRequest): + The initial request object. + response (google.cloud.config_v1.types.ListResourceDriftsResponse): + 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 = config.ListResourceDriftsRequest(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[config.ListResourceDriftsResponse]: + 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[config.ResourceDrift]: + for page in self.pages: + yield from page.resource_drifts + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListResourceDriftsAsyncPager: + """A pager for iterating through ``list_resource_drifts`` requests. + + This class thinly wraps an initial + :class:`google.cloud.config_v1.types.ListResourceDriftsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``resource_drifts`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListResourceDrifts`` requests and continue to iterate + through the ``resource_drifts`` field on the + corresponding responses. + + All the usual :class:`google.cloud.config_v1.types.ListResourceDriftsResponse` + 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[config.ListResourceDriftsResponse]], + request: config.ListResourceDriftsRequest, + response: config.ListResourceDriftsResponse, + *, + 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.config_v1.types.ListResourceDriftsRequest): + The initial request object. + response (google.cloud.config_v1.types.ListResourceDriftsResponse): + 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 = config.ListResourceDriftsRequest(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[config.ListResourceDriftsResponse]: + 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[config.ResourceDrift]: + async def async_generator(): + async for page in self.pages: + for response in page.resource_drifts: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/transports/README.rst b/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/transports/README.rst new file mode 100644 index 000000000000..78e592f08a90 --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`ConfigTransport` is the ABC for all transports. +- public child `ConfigGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `ConfigGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseConfigRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `ConfigRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/transports/__init__.py b/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/transports/__init__.py new file mode 100644 index 000000000000..dae31983d4d2 --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- 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. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import ConfigTransport +from .grpc import ConfigGrpcTransport +from .grpc_asyncio import ConfigGrpcAsyncIOTransport +from .rest import ConfigRestTransport +from .rest import ConfigRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[ConfigTransport]] +_transport_registry['grpc'] = ConfigGrpcTransport +_transport_registry['grpc_asyncio'] = ConfigGrpcAsyncIOTransport +_transport_registry['rest'] = ConfigRestTransport + +__all__ = ( + 'ConfigTransport', + 'ConfigGrpcTransport', + 'ConfigGrpcAsyncIOTransport', + 'ConfigRestTransport', + 'ConfigRestInterceptor', +) diff --git a/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/transports/base.py b/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/transports/base.py new file mode 100644 index 000000000000..6bd22c3c5db9 --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/transports/base.py @@ -0,0 +1,661 @@ +# -*- 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. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +from google.cloud.config_v1 import gapic_version as package_version + +import google.auth # type: ignore +import google.api_core +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.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore +import google.protobuf + +from google.cloud.config_v1.types import config +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class ConfigTransport(abc.ABC): + """Abstract transport class for Config.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'config.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: 'config.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]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + 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. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # 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_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None and not self._ignore_credentials: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # 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 + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_deployments: gapic_v1.method.wrap_method( + self.list_deployments, + default_timeout=None, + client_info=client_info, + ), + self.get_deployment: gapic_v1.method.wrap_method( + self.get_deployment, + default_timeout=None, + client_info=client_info, + ), + self.create_deployment: gapic_v1.method.wrap_method( + self.create_deployment, + default_timeout=None, + client_info=client_info, + ), + self.update_deployment: gapic_v1.method.wrap_method( + self.update_deployment, + default_timeout=None, + client_info=client_info, + ), + self.delete_deployment: gapic_v1.method.wrap_method( + self.delete_deployment, + default_timeout=None, + client_info=client_info, + ), + self.list_revisions: gapic_v1.method.wrap_method( + self.list_revisions, + default_timeout=None, + client_info=client_info, + ), + self.get_revision: gapic_v1.method.wrap_method( + self.get_revision, + default_timeout=None, + client_info=client_info, + ), + self.get_resource: gapic_v1.method.wrap_method( + self.get_resource, + default_timeout=None, + client_info=client_info, + ), + self.list_resources: gapic_v1.method.wrap_method( + self.list_resources, + default_timeout=None, + client_info=client_info, + ), + self.export_deployment_statefile: gapic_v1.method.wrap_method( + self.export_deployment_statefile, + default_timeout=None, + client_info=client_info, + ), + self.export_revision_statefile: gapic_v1.method.wrap_method( + self.export_revision_statefile, + default_timeout=None, + client_info=client_info, + ), + self.import_statefile: gapic_v1.method.wrap_method( + self.import_statefile, + default_timeout=None, + client_info=client_info, + ), + self.delete_statefile: gapic_v1.method.wrap_method( + self.delete_statefile, + default_timeout=None, + client_info=client_info, + ), + self.lock_deployment: gapic_v1.method.wrap_method( + self.lock_deployment, + default_timeout=None, + client_info=client_info, + ), + self.unlock_deployment: gapic_v1.method.wrap_method( + self.unlock_deployment, + default_timeout=None, + client_info=client_info, + ), + self.export_lock_info: gapic_v1.method.wrap_method( + self.export_lock_info, + default_timeout=None, + client_info=client_info, + ), + self.create_preview: gapic_v1.method.wrap_method( + self.create_preview, + default_timeout=None, + client_info=client_info, + ), + self.get_preview: gapic_v1.method.wrap_method( + self.get_preview, + default_timeout=None, + client_info=client_info, + ), + self.list_previews: gapic_v1.method.wrap_method( + self.list_previews, + default_timeout=None, + client_info=client_info, + ), + self.delete_preview: gapic_v1.method.wrap_method( + self.delete_preview, + default_timeout=None, + client_info=client_info, + ), + self.export_preview_result: gapic_v1.method.wrap_method( + self.export_preview_result, + default_timeout=None, + client_info=client_info, + ), + self.list_terraform_versions: gapic_v1.method.wrap_method( + self.list_terraform_versions, + default_timeout=None, + client_info=client_info, + ), + self.get_terraform_version: gapic_v1.method.wrap_method( + self.get_terraform_version, + default_timeout=None, + client_info=client_info, + ), + self.list_resource_changes: gapic_v1.method.wrap_method( + self.list_resource_changes, + default_timeout=None, + client_info=client_info, + ), + self.get_resource_change: gapic_v1.method.wrap_method( + self.get_resource_change, + default_timeout=None, + client_info=client_info, + ), + self.list_resource_drifts: gapic_v1.method.wrap_method( + self.list_resource_drifts, + default_timeout=None, + client_info=client_info, + ), + self.get_resource_drift: gapic_v1.method.wrap_method( + self.get_resource_drift, + 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_deployments(self) -> Callable[ + [config.ListDeploymentsRequest], + Union[ + config.ListDeploymentsResponse, + Awaitable[config.ListDeploymentsResponse] + ]]: + raise NotImplementedError() + + @property + def get_deployment(self) -> Callable[ + [config.GetDeploymentRequest], + Union[ + config.Deployment, + Awaitable[config.Deployment] + ]]: + raise NotImplementedError() + + @property + def create_deployment(self) -> Callable[ + [config.CreateDeploymentRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def update_deployment(self) -> Callable[ + [config.UpdateDeploymentRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_deployment(self) -> Callable[ + [config.DeleteDeploymentRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def list_revisions(self) -> Callable[ + [config.ListRevisionsRequest], + Union[ + config.ListRevisionsResponse, + Awaitable[config.ListRevisionsResponse] + ]]: + raise NotImplementedError() + + @property + def get_revision(self) -> Callable[ + [config.GetRevisionRequest], + Union[ + config.Revision, + Awaitable[config.Revision] + ]]: + raise NotImplementedError() + + @property + def get_resource(self) -> Callable[ + [config.GetResourceRequest], + Union[ + config.Resource, + Awaitable[config.Resource] + ]]: + raise NotImplementedError() + + @property + def list_resources(self) -> Callable[ + [config.ListResourcesRequest], + Union[ + config.ListResourcesResponse, + Awaitable[config.ListResourcesResponse] + ]]: + raise NotImplementedError() + + @property + def export_deployment_statefile(self) -> Callable[ + [config.ExportDeploymentStatefileRequest], + Union[ + config.Statefile, + Awaitable[config.Statefile] + ]]: + raise NotImplementedError() + + @property + def export_revision_statefile(self) -> Callable[ + [config.ExportRevisionStatefileRequest], + Union[ + config.Statefile, + Awaitable[config.Statefile] + ]]: + raise NotImplementedError() + + @property + def import_statefile(self) -> Callable[ + [config.ImportStatefileRequest], + Union[ + config.Statefile, + Awaitable[config.Statefile] + ]]: + raise NotImplementedError() + + @property + def delete_statefile(self) -> Callable[ + [config.DeleteStatefileRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def lock_deployment(self) -> Callable[ + [config.LockDeploymentRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def unlock_deployment(self) -> Callable[ + [config.UnlockDeploymentRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def export_lock_info(self) -> Callable[ + [config.ExportLockInfoRequest], + Union[ + config.LockInfo, + Awaitable[config.LockInfo] + ]]: + raise NotImplementedError() + + @property + def create_preview(self) -> Callable[ + [config.CreatePreviewRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def get_preview(self) -> Callable[ + [config.GetPreviewRequest], + Union[ + config.Preview, + Awaitable[config.Preview] + ]]: + raise NotImplementedError() + + @property + def list_previews(self) -> Callable[ + [config.ListPreviewsRequest], + Union[ + config.ListPreviewsResponse, + Awaitable[config.ListPreviewsResponse] + ]]: + raise NotImplementedError() + + @property + def delete_preview(self) -> Callable[ + [config.DeletePreviewRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def export_preview_result(self) -> Callable[ + [config.ExportPreviewResultRequest], + Union[ + config.ExportPreviewResultResponse, + Awaitable[config.ExportPreviewResultResponse] + ]]: + raise NotImplementedError() + + @property + def list_terraform_versions(self) -> Callable[ + [config.ListTerraformVersionsRequest], + Union[ + config.ListTerraformVersionsResponse, + Awaitable[config.ListTerraformVersionsResponse] + ]]: + raise NotImplementedError() + + @property + def get_terraform_version(self) -> Callable[ + [config.GetTerraformVersionRequest], + Union[ + config.TerraformVersion, + Awaitable[config.TerraformVersion] + ]]: + raise NotImplementedError() + + @property + def list_resource_changes(self) -> Callable[ + [config.ListResourceChangesRequest], + Union[ + config.ListResourceChangesResponse, + Awaitable[config.ListResourceChangesResponse] + ]]: + raise NotImplementedError() + + @property + def get_resource_change(self) -> Callable[ + [config.GetResourceChangeRequest], + Union[ + config.ResourceChange, + Awaitable[config.ResourceChange] + ]]: + raise NotImplementedError() + + @property + def list_resource_drifts(self) -> Callable[ + [config.ListResourceDriftsRequest], + Union[ + config.ListResourceDriftsResponse, + Awaitable[config.ListResourceDriftsResponse] + ]]: + raise NotImplementedError() + + @property + def get_resource_drift(self) -> Callable[ + [config.GetResourceDriftRequest], + Union[ + config.ResourceDrift, + Awaitable[config.ResourceDrift] + ]]: + 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__ = ( + 'ConfigTransport', +) diff --git a/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/transports/grpc.py b/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/transports/grpc.py new file mode 100644 index 000000000000..b8ed39d20f21 --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/transports/grpc.py @@ -0,0 +1,1246 @@ +# -*- 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. +# +import json +import logging as std_logging +import pickle +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import operations_v1 +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.protobuf.json_format import MessageToJson +import google.protobuf.message + +import grpc # type: ignore +import proto # type: ignore + +from google.cloud.config_v1.types import config +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import ConfigTransport, DEFAULT_CLIENT_INFO + +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)}" + + 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.config.v1.Config", + "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)}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response for {client_call_details.method}.", + extra = { + "serviceName": "google.cloud.config.v1.Config", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class ConfigGrpcTransport(ConfigTransport): + """gRPC backend transport for Config. + + Infrastructure Manager is a managed service that automates + the deployment and management of Google Cloud infrastructure + 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 = 'config.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: 'config.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]): 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. + 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. + + 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 = 'config.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]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + 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_deployments(self) -> Callable[ + [config.ListDeploymentsRequest], + config.ListDeploymentsResponse]: + r"""Return a callable for the list deployments method over gRPC. + + Lists [Deployment][google.cloud.config.v1.Deployment]s in a + given project and location. + + Returns: + Callable[[~.ListDeploymentsRequest], + ~.ListDeploymentsResponse]: + 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_deployments' not in self._stubs: + self._stubs['list_deployments'] = self._logged_channel.unary_unary( + '/google.cloud.config.v1.Config/ListDeployments', + request_serializer=config.ListDeploymentsRequest.serialize, + response_deserializer=config.ListDeploymentsResponse.deserialize, + ) + return self._stubs['list_deployments'] + + @property + def get_deployment(self) -> Callable[ + [config.GetDeploymentRequest], + config.Deployment]: + r"""Return a callable for the get deployment method over gRPC. + + Gets details about a + [Deployment][google.cloud.config.v1.Deployment]. + + Returns: + Callable[[~.GetDeploymentRequest], + ~.Deployment]: + 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_deployment' not in self._stubs: + self._stubs['get_deployment'] = self._logged_channel.unary_unary( + '/google.cloud.config.v1.Config/GetDeployment', + request_serializer=config.GetDeploymentRequest.serialize, + response_deserializer=config.Deployment.deserialize, + ) + return self._stubs['get_deployment'] + + @property + def create_deployment(self) -> Callable[ + [config.CreateDeploymentRequest], + operations_pb2.Operation]: + r"""Return a callable for the create deployment method over gRPC. + + Creates a [Deployment][google.cloud.config.v1.Deployment]. + + Returns: + Callable[[~.CreateDeploymentRequest], + ~.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_deployment' not in self._stubs: + self._stubs['create_deployment'] = self._logged_channel.unary_unary( + '/google.cloud.config.v1.Config/CreateDeployment', + request_serializer=config.CreateDeploymentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_deployment'] + + @property + def update_deployment(self) -> Callable[ + [config.UpdateDeploymentRequest], + operations_pb2.Operation]: + r"""Return a callable for the update deployment method over gRPC. + + Updates a [Deployment][google.cloud.config.v1.Deployment]. + + Returns: + Callable[[~.UpdateDeploymentRequest], + ~.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_deployment' not in self._stubs: + self._stubs['update_deployment'] = self._logged_channel.unary_unary( + '/google.cloud.config.v1.Config/UpdateDeployment', + request_serializer=config.UpdateDeploymentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_deployment'] + + @property + def delete_deployment(self) -> Callable[ + [config.DeleteDeploymentRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete deployment method over gRPC. + + Deletes a [Deployment][google.cloud.config.v1.Deployment]. + + Returns: + Callable[[~.DeleteDeploymentRequest], + ~.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_deployment' not in self._stubs: + self._stubs['delete_deployment'] = self._logged_channel.unary_unary( + '/google.cloud.config.v1.Config/DeleteDeployment', + request_serializer=config.DeleteDeploymentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_deployment'] + + @property + def list_revisions(self) -> Callable[ + [config.ListRevisionsRequest], + config.ListRevisionsResponse]: + r"""Return a callable for the list revisions method over gRPC. + + Lists [Revision][google.cloud.config.v1.Revision]s of a + deployment. + + Returns: + Callable[[~.ListRevisionsRequest], + ~.ListRevisionsResponse]: + 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_revisions' not in self._stubs: + self._stubs['list_revisions'] = self._logged_channel.unary_unary( + '/google.cloud.config.v1.Config/ListRevisions', + request_serializer=config.ListRevisionsRequest.serialize, + response_deserializer=config.ListRevisionsResponse.deserialize, + ) + return self._stubs['list_revisions'] + + @property + def get_revision(self) -> Callable[ + [config.GetRevisionRequest], + config.Revision]: + r"""Return a callable for the get revision method over gRPC. + + Gets details about a + [Revision][google.cloud.config.v1.Revision]. + + Returns: + Callable[[~.GetRevisionRequest], + ~.Revision]: + 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_revision' not in self._stubs: + self._stubs['get_revision'] = self._logged_channel.unary_unary( + '/google.cloud.config.v1.Config/GetRevision', + request_serializer=config.GetRevisionRequest.serialize, + response_deserializer=config.Revision.deserialize, + ) + return self._stubs['get_revision'] + + @property + def get_resource(self) -> Callable[ + [config.GetResourceRequest], + config.Resource]: + r"""Return a callable for the get resource method over gRPC. + + Gets details about a [Resource][google.cloud.config.v1.Resource] + deployed by Infra Manager. + + Returns: + Callable[[~.GetResourceRequest], + ~.Resource]: + 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_resource' not in self._stubs: + self._stubs['get_resource'] = self._logged_channel.unary_unary( + '/google.cloud.config.v1.Config/GetResource', + request_serializer=config.GetResourceRequest.serialize, + response_deserializer=config.Resource.deserialize, + ) + return self._stubs['get_resource'] + + @property + def list_resources(self) -> Callable[ + [config.ListResourcesRequest], + config.ListResourcesResponse]: + r"""Return a callable for the list resources method over gRPC. + + Lists [Resources][google.cloud.config.v1.Resource] in a given + revision. + + Returns: + Callable[[~.ListResourcesRequest], + ~.ListResourcesResponse]: + 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_resources' not in self._stubs: + self._stubs['list_resources'] = self._logged_channel.unary_unary( + '/google.cloud.config.v1.Config/ListResources', + request_serializer=config.ListResourcesRequest.serialize, + response_deserializer=config.ListResourcesResponse.deserialize, + ) + return self._stubs['list_resources'] + + @property + def export_deployment_statefile(self) -> Callable[ + [config.ExportDeploymentStatefileRequest], + config.Statefile]: + r"""Return a callable for the export deployment statefile method over gRPC. + + Exports Terraform state file from a given deployment. + + Returns: + Callable[[~.ExportDeploymentStatefileRequest], + ~.Statefile]: + 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 'export_deployment_statefile' not in self._stubs: + self._stubs['export_deployment_statefile'] = self._logged_channel.unary_unary( + '/google.cloud.config.v1.Config/ExportDeploymentStatefile', + request_serializer=config.ExportDeploymentStatefileRequest.serialize, + response_deserializer=config.Statefile.deserialize, + ) + return self._stubs['export_deployment_statefile'] + + @property + def export_revision_statefile(self) -> Callable[ + [config.ExportRevisionStatefileRequest], + config.Statefile]: + r"""Return a callable for the export revision statefile method over gRPC. + + Exports Terraform state file from a given revision. + + Returns: + Callable[[~.ExportRevisionStatefileRequest], + ~.Statefile]: + 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 'export_revision_statefile' not in self._stubs: + self._stubs['export_revision_statefile'] = self._logged_channel.unary_unary( + '/google.cloud.config.v1.Config/ExportRevisionStatefile', + request_serializer=config.ExportRevisionStatefileRequest.serialize, + response_deserializer=config.Statefile.deserialize, + ) + return self._stubs['export_revision_statefile'] + + @property + def import_statefile(self) -> Callable[ + [config.ImportStatefileRequest], + config.Statefile]: + r"""Return a callable for the import statefile method over gRPC. + + Imports Terraform state file in a given deployment. + The state file does not take effect until the Deployment + has been unlocked. + + Returns: + Callable[[~.ImportStatefileRequest], + ~.Statefile]: + 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 'import_statefile' not in self._stubs: + self._stubs['import_statefile'] = self._logged_channel.unary_unary( + '/google.cloud.config.v1.Config/ImportStatefile', + request_serializer=config.ImportStatefileRequest.serialize, + response_deserializer=config.Statefile.deserialize, + ) + return self._stubs['import_statefile'] + + @property + def delete_statefile(self) -> Callable[ + [config.DeleteStatefileRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete statefile method over gRPC. + + Deletes Terraform state file in a given deployment. + + Returns: + Callable[[~.DeleteStatefileRequest], + ~.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_statefile' not in self._stubs: + self._stubs['delete_statefile'] = self._logged_channel.unary_unary( + '/google.cloud.config.v1.Config/DeleteStatefile', + request_serializer=config.DeleteStatefileRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_statefile'] + + @property + def lock_deployment(self) -> Callable[ + [config.LockDeploymentRequest], + operations_pb2.Operation]: + r"""Return a callable for the lock deployment method over gRPC. + + Locks a deployment. + + Returns: + Callable[[~.LockDeploymentRequest], + ~.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 'lock_deployment' not in self._stubs: + self._stubs['lock_deployment'] = self._logged_channel.unary_unary( + '/google.cloud.config.v1.Config/LockDeployment', + request_serializer=config.LockDeploymentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['lock_deployment'] + + @property + def unlock_deployment(self) -> Callable[ + [config.UnlockDeploymentRequest], + operations_pb2.Operation]: + r"""Return a callable for the unlock deployment method over gRPC. + + Unlocks a locked deployment. + + Returns: + Callable[[~.UnlockDeploymentRequest], + ~.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 'unlock_deployment' not in self._stubs: + self._stubs['unlock_deployment'] = self._logged_channel.unary_unary( + '/google.cloud.config.v1.Config/UnlockDeployment', + request_serializer=config.UnlockDeploymentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['unlock_deployment'] + + @property + def export_lock_info(self) -> Callable[ + [config.ExportLockInfoRequest], + config.LockInfo]: + r"""Return a callable for the export lock info method over gRPC. + + Exports the lock info on a locked deployment. + + Returns: + Callable[[~.ExportLockInfoRequest], + ~.LockInfo]: + 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 'export_lock_info' not in self._stubs: + self._stubs['export_lock_info'] = self._logged_channel.unary_unary( + '/google.cloud.config.v1.Config/ExportLockInfo', + request_serializer=config.ExportLockInfoRequest.serialize, + response_deserializer=config.LockInfo.deserialize, + ) + return self._stubs['export_lock_info'] + + @property + def create_preview(self) -> Callable[ + [config.CreatePreviewRequest], + operations_pb2.Operation]: + r"""Return a callable for the create preview method over gRPC. + + Creates a [Preview][google.cloud.config.v1.Preview]. + + Returns: + Callable[[~.CreatePreviewRequest], + ~.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_preview' not in self._stubs: + self._stubs['create_preview'] = self._logged_channel.unary_unary( + '/google.cloud.config.v1.Config/CreatePreview', + request_serializer=config.CreatePreviewRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_preview'] + + @property + def get_preview(self) -> Callable[ + [config.GetPreviewRequest], + config.Preview]: + r"""Return a callable for the get preview method over gRPC. + + Gets details about a [Preview][google.cloud.config.v1.Preview]. + + Returns: + Callable[[~.GetPreviewRequest], + ~.Preview]: + 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_preview' not in self._stubs: + self._stubs['get_preview'] = self._logged_channel.unary_unary( + '/google.cloud.config.v1.Config/GetPreview', + request_serializer=config.GetPreviewRequest.serialize, + response_deserializer=config.Preview.deserialize, + ) + return self._stubs['get_preview'] + + @property + def list_previews(self) -> Callable[ + [config.ListPreviewsRequest], + config.ListPreviewsResponse]: + r"""Return a callable for the list previews method over gRPC. + + Lists [Preview][google.cloud.config.v1.Preview]s in a given + project and location. + + Returns: + Callable[[~.ListPreviewsRequest], + ~.ListPreviewsResponse]: + 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_previews' not in self._stubs: + self._stubs['list_previews'] = self._logged_channel.unary_unary( + '/google.cloud.config.v1.Config/ListPreviews', + request_serializer=config.ListPreviewsRequest.serialize, + response_deserializer=config.ListPreviewsResponse.deserialize, + ) + return self._stubs['list_previews'] + + @property + def delete_preview(self) -> Callable[ + [config.DeletePreviewRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete preview method over gRPC. + + Deletes a [Preview][google.cloud.config.v1.Preview]. + + Returns: + Callable[[~.DeletePreviewRequest], + ~.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_preview' not in self._stubs: + self._stubs['delete_preview'] = self._logged_channel.unary_unary( + '/google.cloud.config.v1.Config/DeletePreview', + request_serializer=config.DeletePreviewRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_preview'] + + @property + def export_preview_result(self) -> Callable[ + [config.ExportPreviewResultRequest], + config.ExportPreviewResultResponse]: + r"""Return a callable for the export preview result method over gRPC. + + Export [Preview][google.cloud.config.v1.Preview] results. + + Returns: + Callable[[~.ExportPreviewResultRequest], + ~.ExportPreviewResultResponse]: + 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 'export_preview_result' not in self._stubs: + self._stubs['export_preview_result'] = self._logged_channel.unary_unary( + '/google.cloud.config.v1.Config/ExportPreviewResult', + request_serializer=config.ExportPreviewResultRequest.serialize, + response_deserializer=config.ExportPreviewResultResponse.deserialize, + ) + return self._stubs['export_preview_result'] + + @property + def list_terraform_versions(self) -> Callable[ + [config.ListTerraformVersionsRequest], + config.ListTerraformVersionsResponse]: + r"""Return a callable for the list terraform versions method over gRPC. + + Lists + [TerraformVersion][google.cloud.config.v1.TerraformVersion]s in + a given project and location. + + Returns: + Callable[[~.ListTerraformVersionsRequest], + ~.ListTerraformVersionsResponse]: + 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_terraform_versions' not in self._stubs: + self._stubs['list_terraform_versions'] = self._logged_channel.unary_unary( + '/google.cloud.config.v1.Config/ListTerraformVersions', + request_serializer=config.ListTerraformVersionsRequest.serialize, + response_deserializer=config.ListTerraformVersionsResponse.deserialize, + ) + return self._stubs['list_terraform_versions'] + + @property + def get_terraform_version(self) -> Callable[ + [config.GetTerraformVersionRequest], + config.TerraformVersion]: + r"""Return a callable for the get terraform version method over gRPC. + + Gets details about a + [TerraformVersion][google.cloud.config.v1.TerraformVersion]. + + Returns: + Callable[[~.GetTerraformVersionRequest], + ~.TerraformVersion]: + 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_terraform_version' not in self._stubs: + self._stubs['get_terraform_version'] = self._logged_channel.unary_unary( + '/google.cloud.config.v1.Config/GetTerraformVersion', + request_serializer=config.GetTerraformVersionRequest.serialize, + response_deserializer=config.TerraformVersion.deserialize, + ) + return self._stubs['get_terraform_version'] + + @property + def list_resource_changes(self) -> Callable[ + [config.ListResourceChangesRequest], + config.ListResourceChangesResponse]: + r"""Return a callable for the list resource changes method over gRPC. + + Lists ResourceChanges for a given preview. + + Returns: + Callable[[~.ListResourceChangesRequest], + ~.ListResourceChangesResponse]: + 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_changes' not in self._stubs: + self._stubs['list_resource_changes'] = self._logged_channel.unary_unary( + '/google.cloud.config.v1.Config/ListResourceChanges', + request_serializer=config.ListResourceChangesRequest.serialize, + response_deserializer=config.ListResourceChangesResponse.deserialize, + ) + return self._stubs['list_resource_changes'] + + @property + def get_resource_change(self) -> Callable[ + [config.GetResourceChangeRequest], + config.ResourceChange]: + r"""Return a callable for the get resource change method over gRPC. + + Get a ResourceChange for a given preview. + + Returns: + Callable[[~.GetResourceChangeRequest], + ~.ResourceChange]: + 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_resource_change' not in self._stubs: + self._stubs['get_resource_change'] = self._logged_channel.unary_unary( + '/google.cloud.config.v1.Config/GetResourceChange', + request_serializer=config.GetResourceChangeRequest.serialize, + response_deserializer=config.ResourceChange.deserialize, + ) + return self._stubs['get_resource_change'] + + @property + def list_resource_drifts(self) -> Callable[ + [config.ListResourceDriftsRequest], + config.ListResourceDriftsResponse]: + r"""Return a callable for the list resource drifts method over gRPC. + + List ResourceDrifts for a given preview. + + Returns: + Callable[[~.ListResourceDriftsRequest], + ~.ListResourceDriftsResponse]: + 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_drifts' not in self._stubs: + self._stubs['list_resource_drifts'] = self._logged_channel.unary_unary( + '/google.cloud.config.v1.Config/ListResourceDrifts', + request_serializer=config.ListResourceDriftsRequest.serialize, + response_deserializer=config.ListResourceDriftsResponse.deserialize, + ) + return self._stubs['list_resource_drifts'] + + @property + def get_resource_drift(self) -> Callable[ + [config.GetResourceDriftRequest], + config.ResourceDrift]: + r"""Return a callable for the get resource drift method over gRPC. + + Get a ResourceDrift for a given preview. + + Returns: + Callable[[~.GetResourceDriftRequest], + ~.ResourceDrift]: + 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_resource_drift' not in self._stubs: + self._stubs['get_resource_drift'] = self._logged_channel.unary_unary( + '/google.cloud.config.v1.Config/GetResourceDrift', + request_serializer=config.GetResourceDriftRequest.serialize, + response_deserializer=config.ResourceDrift.deserialize, + ) + return self._stubs['get_resource_drift'] + + 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__ = ( + 'ConfigGrpcTransport', +) diff --git a/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/transports/grpc_asyncio.py new file mode 100644 index 000000000000..5b8714d9636d --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/transports/grpc_asyncio.py @@ -0,0 +1,1442 @@ +# -*- 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. +# +import inspect +import json +import pickle +import logging as std_logging +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import exceptions as core_exceptions +from google.api_core import retry_async as retries +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.protobuf.json_format import MessageToJson +import google.protobuf.message + +import grpc # type: ignore +import proto # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.config_v1.types import config +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import ConfigTransport, DEFAULT_CLIENT_INFO +from .grpc import ConfigGrpcTransport + +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)}" + + 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.config.v1.Config", + "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)}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response to rpc {client_call_details.method}.", + extra = { + "serviceName": "google.cloud.config.v1.Config", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class ConfigGrpcAsyncIOTransport(ConfigTransport): + """gRPC AsyncIO backend transport for Config. + + Infrastructure Manager is a managed service that automates + the deployment and management of Google Cloud infrastructure + 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 = 'config.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]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + 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 = 'config.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: 'config.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]): 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. + 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. + + 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_deployments(self) -> Callable[ + [config.ListDeploymentsRequest], + Awaitable[config.ListDeploymentsResponse]]: + r"""Return a callable for the list deployments method over gRPC. + + Lists [Deployment][google.cloud.config.v1.Deployment]s in a + given project and location. + + Returns: + Callable[[~.ListDeploymentsRequest], + Awaitable[~.ListDeploymentsResponse]]: + 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_deployments' not in self._stubs: + self._stubs['list_deployments'] = self._logged_channel.unary_unary( + '/google.cloud.config.v1.Config/ListDeployments', + request_serializer=config.ListDeploymentsRequest.serialize, + response_deserializer=config.ListDeploymentsResponse.deserialize, + ) + return self._stubs['list_deployments'] + + @property + def get_deployment(self) -> Callable[ + [config.GetDeploymentRequest], + Awaitable[config.Deployment]]: + r"""Return a callable for the get deployment method over gRPC. + + Gets details about a + [Deployment][google.cloud.config.v1.Deployment]. + + Returns: + Callable[[~.GetDeploymentRequest], + Awaitable[~.Deployment]]: + 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_deployment' not in self._stubs: + self._stubs['get_deployment'] = self._logged_channel.unary_unary( + '/google.cloud.config.v1.Config/GetDeployment', + request_serializer=config.GetDeploymentRequest.serialize, + response_deserializer=config.Deployment.deserialize, + ) + return self._stubs['get_deployment'] + + @property + def create_deployment(self) -> Callable[ + [config.CreateDeploymentRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create deployment method over gRPC. + + Creates a [Deployment][google.cloud.config.v1.Deployment]. + + Returns: + Callable[[~.CreateDeploymentRequest], + 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_deployment' not in self._stubs: + self._stubs['create_deployment'] = self._logged_channel.unary_unary( + '/google.cloud.config.v1.Config/CreateDeployment', + request_serializer=config.CreateDeploymentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_deployment'] + + @property + def update_deployment(self) -> Callable[ + [config.UpdateDeploymentRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the update deployment method over gRPC. + + Updates a [Deployment][google.cloud.config.v1.Deployment]. + + Returns: + Callable[[~.UpdateDeploymentRequest], + 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_deployment' not in self._stubs: + self._stubs['update_deployment'] = self._logged_channel.unary_unary( + '/google.cloud.config.v1.Config/UpdateDeployment', + request_serializer=config.UpdateDeploymentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['update_deployment'] + + @property + def delete_deployment(self) -> Callable[ + [config.DeleteDeploymentRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete deployment method over gRPC. + + Deletes a [Deployment][google.cloud.config.v1.Deployment]. + + Returns: + Callable[[~.DeleteDeploymentRequest], + 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_deployment' not in self._stubs: + self._stubs['delete_deployment'] = self._logged_channel.unary_unary( + '/google.cloud.config.v1.Config/DeleteDeployment', + request_serializer=config.DeleteDeploymentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_deployment'] + + @property + def list_revisions(self) -> Callable[ + [config.ListRevisionsRequest], + Awaitable[config.ListRevisionsResponse]]: + r"""Return a callable for the list revisions method over gRPC. + + Lists [Revision][google.cloud.config.v1.Revision]s of a + deployment. + + Returns: + Callable[[~.ListRevisionsRequest], + Awaitable[~.ListRevisionsResponse]]: + 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_revisions' not in self._stubs: + self._stubs['list_revisions'] = self._logged_channel.unary_unary( + '/google.cloud.config.v1.Config/ListRevisions', + request_serializer=config.ListRevisionsRequest.serialize, + response_deserializer=config.ListRevisionsResponse.deserialize, + ) + return self._stubs['list_revisions'] + + @property + def get_revision(self) -> Callable[ + [config.GetRevisionRequest], + Awaitable[config.Revision]]: + r"""Return a callable for the get revision method over gRPC. + + Gets details about a + [Revision][google.cloud.config.v1.Revision]. + + Returns: + Callable[[~.GetRevisionRequest], + Awaitable[~.Revision]]: + 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_revision' not in self._stubs: + self._stubs['get_revision'] = self._logged_channel.unary_unary( + '/google.cloud.config.v1.Config/GetRevision', + request_serializer=config.GetRevisionRequest.serialize, + response_deserializer=config.Revision.deserialize, + ) + return self._stubs['get_revision'] + + @property + def get_resource(self) -> Callable[ + [config.GetResourceRequest], + Awaitable[config.Resource]]: + r"""Return a callable for the get resource method over gRPC. + + Gets details about a [Resource][google.cloud.config.v1.Resource] + deployed by Infra Manager. + + Returns: + Callable[[~.GetResourceRequest], + Awaitable[~.Resource]]: + 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_resource' not in self._stubs: + self._stubs['get_resource'] = self._logged_channel.unary_unary( + '/google.cloud.config.v1.Config/GetResource', + request_serializer=config.GetResourceRequest.serialize, + response_deserializer=config.Resource.deserialize, + ) + return self._stubs['get_resource'] + + @property + def list_resources(self) -> Callable[ + [config.ListResourcesRequest], + Awaitable[config.ListResourcesResponse]]: + r"""Return a callable for the list resources method over gRPC. + + Lists [Resources][google.cloud.config.v1.Resource] in a given + revision. + + Returns: + Callable[[~.ListResourcesRequest], + Awaitable[~.ListResourcesResponse]]: + 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_resources' not in self._stubs: + self._stubs['list_resources'] = self._logged_channel.unary_unary( + '/google.cloud.config.v1.Config/ListResources', + request_serializer=config.ListResourcesRequest.serialize, + response_deserializer=config.ListResourcesResponse.deserialize, + ) + return self._stubs['list_resources'] + + @property + def export_deployment_statefile(self) -> Callable[ + [config.ExportDeploymentStatefileRequest], + Awaitable[config.Statefile]]: + r"""Return a callable for the export deployment statefile method over gRPC. + + Exports Terraform state file from a given deployment. + + Returns: + Callable[[~.ExportDeploymentStatefileRequest], + Awaitable[~.Statefile]]: + 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 'export_deployment_statefile' not in self._stubs: + self._stubs['export_deployment_statefile'] = self._logged_channel.unary_unary( + '/google.cloud.config.v1.Config/ExportDeploymentStatefile', + request_serializer=config.ExportDeploymentStatefileRequest.serialize, + response_deserializer=config.Statefile.deserialize, + ) + return self._stubs['export_deployment_statefile'] + + @property + def export_revision_statefile(self) -> Callable[ + [config.ExportRevisionStatefileRequest], + Awaitable[config.Statefile]]: + r"""Return a callable for the export revision statefile method over gRPC. + + Exports Terraform state file from a given revision. + + Returns: + Callable[[~.ExportRevisionStatefileRequest], + Awaitable[~.Statefile]]: + 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 'export_revision_statefile' not in self._stubs: + self._stubs['export_revision_statefile'] = self._logged_channel.unary_unary( + '/google.cloud.config.v1.Config/ExportRevisionStatefile', + request_serializer=config.ExportRevisionStatefileRequest.serialize, + response_deserializer=config.Statefile.deserialize, + ) + return self._stubs['export_revision_statefile'] + + @property + def import_statefile(self) -> Callable[ + [config.ImportStatefileRequest], + Awaitable[config.Statefile]]: + r"""Return a callable for the import statefile method over gRPC. + + Imports Terraform state file in a given deployment. + The state file does not take effect until the Deployment + has been unlocked. + + Returns: + Callable[[~.ImportStatefileRequest], + Awaitable[~.Statefile]]: + 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 'import_statefile' not in self._stubs: + self._stubs['import_statefile'] = self._logged_channel.unary_unary( + '/google.cloud.config.v1.Config/ImportStatefile', + request_serializer=config.ImportStatefileRequest.serialize, + response_deserializer=config.Statefile.deserialize, + ) + return self._stubs['import_statefile'] + + @property + def delete_statefile(self) -> Callable[ + [config.DeleteStatefileRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete statefile method over gRPC. + + Deletes Terraform state file in a given deployment. + + Returns: + Callable[[~.DeleteStatefileRequest], + 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_statefile' not in self._stubs: + self._stubs['delete_statefile'] = self._logged_channel.unary_unary( + '/google.cloud.config.v1.Config/DeleteStatefile', + request_serializer=config.DeleteStatefileRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_statefile'] + + @property + def lock_deployment(self) -> Callable[ + [config.LockDeploymentRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the lock deployment method over gRPC. + + Locks a deployment. + + Returns: + Callable[[~.LockDeploymentRequest], + 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 'lock_deployment' not in self._stubs: + self._stubs['lock_deployment'] = self._logged_channel.unary_unary( + '/google.cloud.config.v1.Config/LockDeployment', + request_serializer=config.LockDeploymentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['lock_deployment'] + + @property + def unlock_deployment(self) -> Callable[ + [config.UnlockDeploymentRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the unlock deployment method over gRPC. + + Unlocks a locked deployment. + + Returns: + Callable[[~.UnlockDeploymentRequest], + 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 'unlock_deployment' not in self._stubs: + self._stubs['unlock_deployment'] = self._logged_channel.unary_unary( + '/google.cloud.config.v1.Config/UnlockDeployment', + request_serializer=config.UnlockDeploymentRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['unlock_deployment'] + + @property + def export_lock_info(self) -> Callable[ + [config.ExportLockInfoRequest], + Awaitable[config.LockInfo]]: + r"""Return a callable for the export lock info method over gRPC. + + Exports the lock info on a locked deployment. + + Returns: + Callable[[~.ExportLockInfoRequest], + Awaitable[~.LockInfo]]: + 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 'export_lock_info' not in self._stubs: + self._stubs['export_lock_info'] = self._logged_channel.unary_unary( + '/google.cloud.config.v1.Config/ExportLockInfo', + request_serializer=config.ExportLockInfoRequest.serialize, + response_deserializer=config.LockInfo.deserialize, + ) + return self._stubs['export_lock_info'] + + @property + def create_preview(self) -> Callable[ + [config.CreatePreviewRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create preview method over gRPC. + + Creates a [Preview][google.cloud.config.v1.Preview]. + + Returns: + Callable[[~.CreatePreviewRequest], + 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_preview' not in self._stubs: + self._stubs['create_preview'] = self._logged_channel.unary_unary( + '/google.cloud.config.v1.Config/CreatePreview', + request_serializer=config.CreatePreviewRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_preview'] + + @property + def get_preview(self) -> Callable[ + [config.GetPreviewRequest], + Awaitable[config.Preview]]: + r"""Return a callable for the get preview method over gRPC. + + Gets details about a [Preview][google.cloud.config.v1.Preview]. + + Returns: + Callable[[~.GetPreviewRequest], + Awaitable[~.Preview]]: + 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_preview' not in self._stubs: + self._stubs['get_preview'] = self._logged_channel.unary_unary( + '/google.cloud.config.v1.Config/GetPreview', + request_serializer=config.GetPreviewRequest.serialize, + response_deserializer=config.Preview.deserialize, + ) + return self._stubs['get_preview'] + + @property + def list_previews(self) -> Callable[ + [config.ListPreviewsRequest], + Awaitable[config.ListPreviewsResponse]]: + r"""Return a callable for the list previews method over gRPC. + + Lists [Preview][google.cloud.config.v1.Preview]s in a given + project and location. + + Returns: + Callable[[~.ListPreviewsRequest], + Awaitable[~.ListPreviewsResponse]]: + 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_previews' not in self._stubs: + self._stubs['list_previews'] = self._logged_channel.unary_unary( + '/google.cloud.config.v1.Config/ListPreviews', + request_serializer=config.ListPreviewsRequest.serialize, + response_deserializer=config.ListPreviewsResponse.deserialize, + ) + return self._stubs['list_previews'] + + @property + def delete_preview(self) -> Callable[ + [config.DeletePreviewRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete preview method over gRPC. + + Deletes a [Preview][google.cloud.config.v1.Preview]. + + Returns: + Callable[[~.DeletePreviewRequest], + 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_preview' not in self._stubs: + self._stubs['delete_preview'] = self._logged_channel.unary_unary( + '/google.cloud.config.v1.Config/DeletePreview', + request_serializer=config.DeletePreviewRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_preview'] + + @property + def export_preview_result(self) -> Callable[ + [config.ExportPreviewResultRequest], + Awaitable[config.ExportPreviewResultResponse]]: + r"""Return a callable for the export preview result method over gRPC. + + Export [Preview][google.cloud.config.v1.Preview] results. + + Returns: + Callable[[~.ExportPreviewResultRequest], + Awaitable[~.ExportPreviewResultResponse]]: + 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 'export_preview_result' not in self._stubs: + self._stubs['export_preview_result'] = self._logged_channel.unary_unary( + '/google.cloud.config.v1.Config/ExportPreviewResult', + request_serializer=config.ExportPreviewResultRequest.serialize, + response_deserializer=config.ExportPreviewResultResponse.deserialize, + ) + return self._stubs['export_preview_result'] + + @property + def list_terraform_versions(self) -> Callable[ + [config.ListTerraformVersionsRequest], + Awaitable[config.ListTerraformVersionsResponse]]: + r"""Return a callable for the list terraform versions method over gRPC. + + Lists + [TerraformVersion][google.cloud.config.v1.TerraformVersion]s in + a given project and location. + + Returns: + Callable[[~.ListTerraformVersionsRequest], + Awaitable[~.ListTerraformVersionsResponse]]: + 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_terraform_versions' not in self._stubs: + self._stubs['list_terraform_versions'] = self._logged_channel.unary_unary( + '/google.cloud.config.v1.Config/ListTerraformVersions', + request_serializer=config.ListTerraformVersionsRequest.serialize, + response_deserializer=config.ListTerraformVersionsResponse.deserialize, + ) + return self._stubs['list_terraform_versions'] + + @property + def get_terraform_version(self) -> Callable[ + [config.GetTerraformVersionRequest], + Awaitable[config.TerraformVersion]]: + r"""Return a callable for the get terraform version method over gRPC. + + Gets details about a + [TerraformVersion][google.cloud.config.v1.TerraformVersion]. + + Returns: + Callable[[~.GetTerraformVersionRequest], + Awaitable[~.TerraformVersion]]: + 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_terraform_version' not in self._stubs: + self._stubs['get_terraform_version'] = self._logged_channel.unary_unary( + '/google.cloud.config.v1.Config/GetTerraformVersion', + request_serializer=config.GetTerraformVersionRequest.serialize, + response_deserializer=config.TerraformVersion.deserialize, + ) + return self._stubs['get_terraform_version'] + + @property + def list_resource_changes(self) -> Callable[ + [config.ListResourceChangesRequest], + Awaitable[config.ListResourceChangesResponse]]: + r"""Return a callable for the list resource changes method over gRPC. + + Lists ResourceChanges for a given preview. + + Returns: + Callable[[~.ListResourceChangesRequest], + Awaitable[~.ListResourceChangesResponse]]: + 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_changes' not in self._stubs: + self._stubs['list_resource_changes'] = self._logged_channel.unary_unary( + '/google.cloud.config.v1.Config/ListResourceChanges', + request_serializer=config.ListResourceChangesRequest.serialize, + response_deserializer=config.ListResourceChangesResponse.deserialize, + ) + return self._stubs['list_resource_changes'] + + @property + def get_resource_change(self) -> Callable[ + [config.GetResourceChangeRequest], + Awaitable[config.ResourceChange]]: + r"""Return a callable for the get resource change method over gRPC. + + Get a ResourceChange for a given preview. + + Returns: + Callable[[~.GetResourceChangeRequest], + Awaitable[~.ResourceChange]]: + 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_resource_change' not in self._stubs: + self._stubs['get_resource_change'] = self._logged_channel.unary_unary( + '/google.cloud.config.v1.Config/GetResourceChange', + request_serializer=config.GetResourceChangeRequest.serialize, + response_deserializer=config.ResourceChange.deserialize, + ) + return self._stubs['get_resource_change'] + + @property + def list_resource_drifts(self) -> Callable[ + [config.ListResourceDriftsRequest], + Awaitable[config.ListResourceDriftsResponse]]: + r"""Return a callable for the list resource drifts method over gRPC. + + List ResourceDrifts for a given preview. + + Returns: + Callable[[~.ListResourceDriftsRequest], + Awaitable[~.ListResourceDriftsResponse]]: + 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_drifts' not in self._stubs: + self._stubs['list_resource_drifts'] = self._logged_channel.unary_unary( + '/google.cloud.config.v1.Config/ListResourceDrifts', + request_serializer=config.ListResourceDriftsRequest.serialize, + response_deserializer=config.ListResourceDriftsResponse.deserialize, + ) + return self._stubs['list_resource_drifts'] + + @property + def get_resource_drift(self) -> Callable[ + [config.GetResourceDriftRequest], + Awaitable[config.ResourceDrift]]: + r"""Return a callable for the get resource drift method over gRPC. + + Get a ResourceDrift for a given preview. + + Returns: + Callable[[~.GetResourceDriftRequest], + Awaitable[~.ResourceDrift]]: + 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_resource_drift' not in self._stubs: + self._stubs['get_resource_drift'] = self._logged_channel.unary_unary( + '/google.cloud.config.v1.Config/GetResourceDrift', + request_serializer=config.GetResourceDriftRequest.serialize, + response_deserializer=config.ResourceDrift.deserialize, + ) + return self._stubs['get_resource_drift'] + + 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_deployments: self._wrap_method( + self.list_deployments, + default_timeout=None, + client_info=client_info, + ), + self.get_deployment: self._wrap_method( + self.get_deployment, + default_timeout=None, + client_info=client_info, + ), + self.create_deployment: self._wrap_method( + self.create_deployment, + default_timeout=None, + client_info=client_info, + ), + self.update_deployment: self._wrap_method( + self.update_deployment, + default_timeout=None, + client_info=client_info, + ), + self.delete_deployment: self._wrap_method( + self.delete_deployment, + default_timeout=None, + client_info=client_info, + ), + self.list_revisions: self._wrap_method( + self.list_revisions, + default_timeout=None, + client_info=client_info, + ), + self.get_revision: self._wrap_method( + self.get_revision, + default_timeout=None, + client_info=client_info, + ), + self.get_resource: self._wrap_method( + self.get_resource, + default_timeout=None, + client_info=client_info, + ), + self.list_resources: self._wrap_method( + self.list_resources, + default_timeout=None, + client_info=client_info, + ), + self.export_deployment_statefile: self._wrap_method( + self.export_deployment_statefile, + default_timeout=None, + client_info=client_info, + ), + self.export_revision_statefile: self._wrap_method( + self.export_revision_statefile, + default_timeout=None, + client_info=client_info, + ), + self.import_statefile: self._wrap_method( + self.import_statefile, + default_timeout=None, + client_info=client_info, + ), + self.delete_statefile: self._wrap_method( + self.delete_statefile, + default_timeout=None, + client_info=client_info, + ), + self.lock_deployment: self._wrap_method( + self.lock_deployment, + default_timeout=None, + client_info=client_info, + ), + self.unlock_deployment: self._wrap_method( + self.unlock_deployment, + default_timeout=None, + client_info=client_info, + ), + self.export_lock_info: self._wrap_method( + self.export_lock_info, + default_timeout=None, + client_info=client_info, + ), + self.create_preview: self._wrap_method( + self.create_preview, + default_timeout=None, + client_info=client_info, + ), + self.get_preview: self._wrap_method( + self.get_preview, + default_timeout=None, + client_info=client_info, + ), + self.list_previews: self._wrap_method( + self.list_previews, + default_timeout=None, + client_info=client_info, + ), + self.delete_preview: self._wrap_method( + self.delete_preview, + default_timeout=None, + client_info=client_info, + ), + self.export_preview_result: self._wrap_method( + self.export_preview_result, + default_timeout=None, + client_info=client_info, + ), + self.list_terraform_versions: self._wrap_method( + self.list_terraform_versions, + default_timeout=None, + client_info=client_info, + ), + self.get_terraform_version: self._wrap_method( + self.get_terraform_version, + default_timeout=None, + client_info=client_info, + ), + self.list_resource_changes: self._wrap_method( + self.list_resource_changes, + default_timeout=None, + client_info=client_info, + ), + self.get_resource_change: self._wrap_method( + self.get_resource_change, + default_timeout=None, + client_info=client_info, + ), + self.list_resource_drifts: self._wrap_method( + self.list_resource_drifts, + default_timeout=None, + client_info=client_info, + ), + self.get_resource_drift: self._wrap_method( + self.get_resource_drift, + 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__ = ( + 'ConfigGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/transports/rest.py b/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/transports/rest.py new file mode 100644 index 000000000000..1ce4c3930e23 --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/transports/rest.py @@ -0,0 +1,6103 @@ +# -*- 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. +# +import logging +import json # type: ignore + +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import gapic_v1 +import google.protobuf + +from google.protobuf import json_format +from google.api_core import operations_v1 +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore + +from requests import __version__ as requests_version +import dataclasses +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + + +from google.cloud.config_v1.types import config +from google.protobuf import empty_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + + +from .rest_base import _BaseConfigRestTransport +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + +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}", +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class ConfigRestInterceptor: + """Interceptor for Config. + + 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 ConfigRestTransport. + + .. code-block:: python + class MyCustomConfigInterceptor(ConfigRestInterceptor): + def pre_create_deployment(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_deployment(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_preview(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_preview(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_deployment(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_deployment(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_preview(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_preview(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_statefile(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_export_deployment_statefile(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_export_deployment_statefile(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_export_lock_info(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_export_lock_info(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_export_preview_result(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_export_preview_result(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_export_revision_statefile(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_export_revision_statefile(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_deployment(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_deployment(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_preview(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_preview(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_resource(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_resource(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_resource_change(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_resource_change(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_resource_drift(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_resource_drift(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_revision(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_revision(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_terraform_version(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_terraform_version(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_import_statefile(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_import_statefile(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_deployments(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_deployments(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_previews(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_previews(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_resource_changes(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_resource_changes(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_resource_drifts(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_resource_drifts(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_resources(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_resources(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_revisions(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_revisions(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_terraform_versions(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_terraform_versions(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_lock_deployment(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_lock_deployment(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_unlock_deployment(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_unlock_deployment(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_deployment(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_deployment(self, response): + logging.log(f"Received response: {response}") + return response + + transport = ConfigRestTransport(interceptor=MyCustomConfigInterceptor()) + client = ConfigClient(transport=transport) + + + """ + def pre_create_deployment(self, request: config.CreateDeploymentRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[config.CreateDeploymentRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for create_deployment + + Override in a subclass to manipulate the request or metadata + before they are sent to the Config server. + """ + return request, metadata + + def post_create_deployment(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_deployment + + DEPRECATED. Please use the `post_create_deployment_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Config server but before + it is returned to user code. This `post_create_deployment` interceptor runs + before the `post_create_deployment_with_metadata` interceptor. + """ + return response + + def post_create_deployment_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_deployment + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Config server but before it is returned to user code. + + We recommend only using this `post_create_deployment_with_metadata` + interceptor in new development instead of the `post_create_deployment` interceptor. + When both interceptors are used, this `post_create_deployment_with_metadata` interceptor runs after the + `post_create_deployment` interceptor. The (possibly modified) response returned by + `post_create_deployment` will be passed to + `post_create_deployment_with_metadata`. + """ + return response, metadata + + def pre_create_preview(self, request: config.CreatePreviewRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[config.CreatePreviewRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for create_preview + + Override in a subclass to manipulate the request or metadata + before they are sent to the Config server. + """ + return request, metadata + + def post_create_preview(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_preview + + DEPRECATED. Please use the `post_create_preview_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Config server but before + it is returned to user code. This `post_create_preview` interceptor runs + before the `post_create_preview_with_metadata` interceptor. + """ + return response + + def post_create_preview_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_preview + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Config server but before it is returned to user code. + + We recommend only using this `post_create_preview_with_metadata` + interceptor in new development instead of the `post_create_preview` interceptor. + When both interceptors are used, this `post_create_preview_with_metadata` interceptor runs after the + `post_create_preview` interceptor. The (possibly modified) response returned by + `post_create_preview` will be passed to + `post_create_preview_with_metadata`. + """ + return response, metadata + + def pre_delete_deployment(self, request: config.DeleteDeploymentRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[config.DeleteDeploymentRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for delete_deployment + + Override in a subclass to manipulate the request or metadata + before they are sent to the Config server. + """ + return request, metadata + + def post_delete_deployment(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_deployment + + DEPRECATED. Please use the `post_delete_deployment_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Config server but before + it is returned to user code. This `post_delete_deployment` interceptor runs + before the `post_delete_deployment_with_metadata` interceptor. + """ + return response + + def post_delete_deployment_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_deployment + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Config server but before it is returned to user code. + + We recommend only using this `post_delete_deployment_with_metadata` + interceptor in new development instead of the `post_delete_deployment` interceptor. + When both interceptors are used, this `post_delete_deployment_with_metadata` interceptor runs after the + `post_delete_deployment` interceptor. The (possibly modified) response returned by + `post_delete_deployment` will be passed to + `post_delete_deployment_with_metadata`. + """ + return response, metadata + + def pre_delete_preview(self, request: config.DeletePreviewRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[config.DeletePreviewRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for delete_preview + + Override in a subclass to manipulate the request or metadata + before they are sent to the Config server. + """ + return request, metadata + + def post_delete_preview(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_preview + + DEPRECATED. Please use the `post_delete_preview_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Config server but before + it is returned to user code. This `post_delete_preview` interceptor runs + before the `post_delete_preview_with_metadata` interceptor. + """ + return response + + def post_delete_preview_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_preview + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Config server but before it is returned to user code. + + We recommend only using this `post_delete_preview_with_metadata` + interceptor in new development instead of the `post_delete_preview` interceptor. + When both interceptors are used, this `post_delete_preview_with_metadata` interceptor runs after the + `post_delete_preview` interceptor. The (possibly modified) response returned by + `post_delete_preview` will be passed to + `post_delete_preview_with_metadata`. + """ + return response, metadata + + def pre_delete_statefile(self, request: config.DeleteStatefileRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[config.DeleteStatefileRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for delete_statefile + + Override in a subclass to manipulate the request or metadata + before they are sent to the Config server. + """ + return request, metadata + + def pre_export_deployment_statefile(self, request: config.ExportDeploymentStatefileRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[config.ExportDeploymentStatefileRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for export_deployment_statefile + + Override in a subclass to manipulate the request or metadata + before they are sent to the Config server. + """ + return request, metadata + + def post_export_deployment_statefile(self, response: config.Statefile) -> config.Statefile: + """Post-rpc interceptor for export_deployment_statefile + + DEPRECATED. Please use the `post_export_deployment_statefile_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Config server but before + it is returned to user code. This `post_export_deployment_statefile` interceptor runs + before the `post_export_deployment_statefile_with_metadata` interceptor. + """ + return response + + def post_export_deployment_statefile_with_metadata(self, response: config.Statefile, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[config.Statefile, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for export_deployment_statefile + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Config server but before it is returned to user code. + + We recommend only using this `post_export_deployment_statefile_with_metadata` + interceptor in new development instead of the `post_export_deployment_statefile` interceptor. + When both interceptors are used, this `post_export_deployment_statefile_with_metadata` interceptor runs after the + `post_export_deployment_statefile` interceptor. The (possibly modified) response returned by + `post_export_deployment_statefile` will be passed to + `post_export_deployment_statefile_with_metadata`. + """ + return response, metadata + + def pre_export_lock_info(self, request: config.ExportLockInfoRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[config.ExportLockInfoRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for export_lock_info + + Override in a subclass to manipulate the request or metadata + before they are sent to the Config server. + """ + return request, metadata + + def post_export_lock_info(self, response: config.LockInfo) -> config.LockInfo: + """Post-rpc interceptor for export_lock_info + + DEPRECATED. Please use the `post_export_lock_info_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Config server but before + it is returned to user code. This `post_export_lock_info` interceptor runs + before the `post_export_lock_info_with_metadata` interceptor. + """ + return response + + def post_export_lock_info_with_metadata(self, response: config.LockInfo, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[config.LockInfo, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for export_lock_info + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Config server but before it is returned to user code. + + We recommend only using this `post_export_lock_info_with_metadata` + interceptor in new development instead of the `post_export_lock_info` interceptor. + When both interceptors are used, this `post_export_lock_info_with_metadata` interceptor runs after the + `post_export_lock_info` interceptor. The (possibly modified) response returned by + `post_export_lock_info` will be passed to + `post_export_lock_info_with_metadata`. + """ + return response, metadata + + def pre_export_preview_result(self, request: config.ExportPreviewResultRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[config.ExportPreviewResultRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for export_preview_result + + Override in a subclass to manipulate the request or metadata + before they are sent to the Config server. + """ + return request, metadata + + def post_export_preview_result(self, response: config.ExportPreviewResultResponse) -> config.ExportPreviewResultResponse: + """Post-rpc interceptor for export_preview_result + + DEPRECATED. Please use the `post_export_preview_result_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Config server but before + it is returned to user code. This `post_export_preview_result` interceptor runs + before the `post_export_preview_result_with_metadata` interceptor. + """ + return response + + def post_export_preview_result_with_metadata(self, response: config.ExportPreviewResultResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[config.ExportPreviewResultResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for export_preview_result + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Config server but before it is returned to user code. + + We recommend only using this `post_export_preview_result_with_metadata` + interceptor in new development instead of the `post_export_preview_result` interceptor. + When both interceptors are used, this `post_export_preview_result_with_metadata` interceptor runs after the + `post_export_preview_result` interceptor. The (possibly modified) response returned by + `post_export_preview_result` will be passed to + `post_export_preview_result_with_metadata`. + """ + return response, metadata + + def pre_export_revision_statefile(self, request: config.ExportRevisionStatefileRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[config.ExportRevisionStatefileRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for export_revision_statefile + + Override in a subclass to manipulate the request or metadata + before they are sent to the Config server. + """ + return request, metadata + + def post_export_revision_statefile(self, response: config.Statefile) -> config.Statefile: + """Post-rpc interceptor for export_revision_statefile + + DEPRECATED. Please use the `post_export_revision_statefile_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Config server but before + it is returned to user code. This `post_export_revision_statefile` interceptor runs + before the `post_export_revision_statefile_with_metadata` interceptor. + """ + return response + + def post_export_revision_statefile_with_metadata(self, response: config.Statefile, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[config.Statefile, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for export_revision_statefile + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Config server but before it is returned to user code. + + We recommend only using this `post_export_revision_statefile_with_metadata` + interceptor in new development instead of the `post_export_revision_statefile` interceptor. + When both interceptors are used, this `post_export_revision_statefile_with_metadata` interceptor runs after the + `post_export_revision_statefile` interceptor. The (possibly modified) response returned by + `post_export_revision_statefile` will be passed to + `post_export_revision_statefile_with_metadata`. + """ + return response, metadata + + def pre_get_deployment(self, request: config.GetDeploymentRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[config.GetDeploymentRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_deployment + + Override in a subclass to manipulate the request or metadata + before they are sent to the Config server. + """ + return request, metadata + + def post_get_deployment(self, response: config.Deployment) -> config.Deployment: + """Post-rpc interceptor for get_deployment + + DEPRECATED. Please use the `post_get_deployment_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Config server but before + it is returned to user code. This `post_get_deployment` interceptor runs + before the `post_get_deployment_with_metadata` interceptor. + """ + return response + + def post_get_deployment_with_metadata(self, response: config.Deployment, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[config.Deployment, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_deployment + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Config server but before it is returned to user code. + + We recommend only using this `post_get_deployment_with_metadata` + interceptor in new development instead of the `post_get_deployment` interceptor. + When both interceptors are used, this `post_get_deployment_with_metadata` interceptor runs after the + `post_get_deployment` interceptor. The (possibly modified) response returned by + `post_get_deployment` will be passed to + `post_get_deployment_with_metadata`. + """ + return response, metadata + + def pre_get_preview(self, request: config.GetPreviewRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[config.GetPreviewRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_preview + + Override in a subclass to manipulate the request or metadata + before they are sent to the Config server. + """ + return request, metadata + + def post_get_preview(self, response: config.Preview) -> config.Preview: + """Post-rpc interceptor for get_preview + + DEPRECATED. Please use the `post_get_preview_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Config server but before + it is returned to user code. This `post_get_preview` interceptor runs + before the `post_get_preview_with_metadata` interceptor. + """ + return response + + def post_get_preview_with_metadata(self, response: config.Preview, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[config.Preview, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_preview + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Config server but before it is returned to user code. + + We recommend only using this `post_get_preview_with_metadata` + interceptor in new development instead of the `post_get_preview` interceptor. + When both interceptors are used, this `post_get_preview_with_metadata` interceptor runs after the + `post_get_preview` interceptor. The (possibly modified) response returned by + `post_get_preview` will be passed to + `post_get_preview_with_metadata`. + """ + return response, metadata + + def pre_get_resource(self, request: config.GetResourceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[config.GetResourceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_resource + + Override in a subclass to manipulate the request or metadata + before they are sent to the Config server. + """ + return request, metadata + + def post_get_resource(self, response: config.Resource) -> config.Resource: + """Post-rpc interceptor for get_resource + + DEPRECATED. Please use the `post_get_resource_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Config server but before + it is returned to user code. This `post_get_resource` interceptor runs + before the `post_get_resource_with_metadata` interceptor. + """ + return response + + def post_get_resource_with_metadata(self, response: config.Resource, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[config.Resource, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_resource + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Config server but before it is returned to user code. + + We recommend only using this `post_get_resource_with_metadata` + interceptor in new development instead of the `post_get_resource` interceptor. + When both interceptors are used, this `post_get_resource_with_metadata` interceptor runs after the + `post_get_resource` interceptor. The (possibly modified) response returned by + `post_get_resource` will be passed to + `post_get_resource_with_metadata`. + """ + return response, metadata + + def pre_get_resource_change(self, request: config.GetResourceChangeRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[config.GetResourceChangeRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_resource_change + + Override in a subclass to manipulate the request or metadata + before they are sent to the Config server. + """ + return request, metadata + + def post_get_resource_change(self, response: config.ResourceChange) -> config.ResourceChange: + """Post-rpc interceptor for get_resource_change + + DEPRECATED. Please use the `post_get_resource_change_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Config server but before + it is returned to user code. This `post_get_resource_change` interceptor runs + before the `post_get_resource_change_with_metadata` interceptor. + """ + return response + + def post_get_resource_change_with_metadata(self, response: config.ResourceChange, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[config.ResourceChange, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_resource_change + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Config server but before it is returned to user code. + + We recommend only using this `post_get_resource_change_with_metadata` + interceptor in new development instead of the `post_get_resource_change` interceptor. + When both interceptors are used, this `post_get_resource_change_with_metadata` interceptor runs after the + `post_get_resource_change` interceptor. The (possibly modified) response returned by + `post_get_resource_change` will be passed to + `post_get_resource_change_with_metadata`. + """ + return response, metadata + + def pre_get_resource_drift(self, request: config.GetResourceDriftRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[config.GetResourceDriftRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_resource_drift + + Override in a subclass to manipulate the request or metadata + before they are sent to the Config server. + """ + return request, metadata + + def post_get_resource_drift(self, response: config.ResourceDrift) -> config.ResourceDrift: + """Post-rpc interceptor for get_resource_drift + + DEPRECATED. Please use the `post_get_resource_drift_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Config server but before + it is returned to user code. This `post_get_resource_drift` interceptor runs + before the `post_get_resource_drift_with_metadata` interceptor. + """ + return response + + def post_get_resource_drift_with_metadata(self, response: config.ResourceDrift, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[config.ResourceDrift, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_resource_drift + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Config server but before it is returned to user code. + + We recommend only using this `post_get_resource_drift_with_metadata` + interceptor in new development instead of the `post_get_resource_drift` interceptor. + When both interceptors are used, this `post_get_resource_drift_with_metadata` interceptor runs after the + `post_get_resource_drift` interceptor. The (possibly modified) response returned by + `post_get_resource_drift` will be passed to + `post_get_resource_drift_with_metadata`. + """ + return response, metadata + + def pre_get_revision(self, request: config.GetRevisionRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[config.GetRevisionRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_revision + + Override in a subclass to manipulate the request or metadata + before they are sent to the Config server. + """ + return request, metadata + + def post_get_revision(self, response: config.Revision) -> config.Revision: + """Post-rpc interceptor for get_revision + + DEPRECATED. Please use the `post_get_revision_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Config server but before + it is returned to user code. This `post_get_revision` interceptor runs + before the `post_get_revision_with_metadata` interceptor. + """ + return response + + def post_get_revision_with_metadata(self, response: config.Revision, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[config.Revision, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_revision + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Config server but before it is returned to user code. + + We recommend only using this `post_get_revision_with_metadata` + interceptor in new development instead of the `post_get_revision` interceptor. + When both interceptors are used, this `post_get_revision_with_metadata` interceptor runs after the + `post_get_revision` interceptor. The (possibly modified) response returned by + `post_get_revision` will be passed to + `post_get_revision_with_metadata`. + """ + return response, metadata + + def pre_get_terraform_version(self, request: config.GetTerraformVersionRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[config.GetTerraformVersionRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_terraform_version + + Override in a subclass to manipulate the request or metadata + before they are sent to the Config server. + """ + return request, metadata + + def post_get_terraform_version(self, response: config.TerraformVersion) -> config.TerraformVersion: + """Post-rpc interceptor for get_terraform_version + + DEPRECATED. Please use the `post_get_terraform_version_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Config server but before + it is returned to user code. This `post_get_terraform_version` interceptor runs + before the `post_get_terraform_version_with_metadata` interceptor. + """ + return response + + def post_get_terraform_version_with_metadata(self, response: config.TerraformVersion, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[config.TerraformVersion, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_terraform_version + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Config server but before it is returned to user code. + + We recommend only using this `post_get_terraform_version_with_metadata` + interceptor in new development instead of the `post_get_terraform_version` interceptor. + When both interceptors are used, this `post_get_terraform_version_with_metadata` interceptor runs after the + `post_get_terraform_version` interceptor. The (possibly modified) response returned by + `post_get_terraform_version` will be passed to + `post_get_terraform_version_with_metadata`. + """ + return response, metadata + + def pre_import_statefile(self, request: config.ImportStatefileRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[config.ImportStatefileRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for import_statefile + + Override in a subclass to manipulate the request or metadata + before they are sent to the Config server. + """ + return request, metadata + + def post_import_statefile(self, response: config.Statefile) -> config.Statefile: + """Post-rpc interceptor for import_statefile + + DEPRECATED. Please use the `post_import_statefile_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Config server but before + it is returned to user code. This `post_import_statefile` interceptor runs + before the `post_import_statefile_with_metadata` interceptor. + """ + return response + + def post_import_statefile_with_metadata(self, response: config.Statefile, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[config.Statefile, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for import_statefile + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Config server but before it is returned to user code. + + We recommend only using this `post_import_statefile_with_metadata` + interceptor in new development instead of the `post_import_statefile` interceptor. + When both interceptors are used, this `post_import_statefile_with_metadata` interceptor runs after the + `post_import_statefile` interceptor. The (possibly modified) response returned by + `post_import_statefile` will be passed to + `post_import_statefile_with_metadata`. + """ + return response, metadata + + def pre_list_deployments(self, request: config.ListDeploymentsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[config.ListDeploymentsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_deployments + + Override in a subclass to manipulate the request or metadata + before they are sent to the Config server. + """ + return request, metadata + + def post_list_deployments(self, response: config.ListDeploymentsResponse) -> config.ListDeploymentsResponse: + """Post-rpc interceptor for list_deployments + + DEPRECATED. Please use the `post_list_deployments_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Config server but before + it is returned to user code. This `post_list_deployments` interceptor runs + before the `post_list_deployments_with_metadata` interceptor. + """ + return response + + def post_list_deployments_with_metadata(self, response: config.ListDeploymentsResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[config.ListDeploymentsResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for list_deployments + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Config server but before it is returned to user code. + + We recommend only using this `post_list_deployments_with_metadata` + interceptor in new development instead of the `post_list_deployments` interceptor. + When both interceptors are used, this `post_list_deployments_with_metadata` interceptor runs after the + `post_list_deployments` interceptor. The (possibly modified) response returned by + `post_list_deployments` will be passed to + `post_list_deployments_with_metadata`. + """ + return response, metadata + + def pre_list_previews(self, request: config.ListPreviewsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[config.ListPreviewsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_previews + + Override in a subclass to manipulate the request or metadata + before they are sent to the Config server. + """ + return request, metadata + + def post_list_previews(self, response: config.ListPreviewsResponse) -> config.ListPreviewsResponse: + """Post-rpc interceptor for list_previews + + DEPRECATED. Please use the `post_list_previews_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Config server but before + it is returned to user code. This `post_list_previews` interceptor runs + before the `post_list_previews_with_metadata` interceptor. + """ + return response + + def post_list_previews_with_metadata(self, response: config.ListPreviewsResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[config.ListPreviewsResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for list_previews + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Config server but before it is returned to user code. + + We recommend only using this `post_list_previews_with_metadata` + interceptor in new development instead of the `post_list_previews` interceptor. + When both interceptors are used, this `post_list_previews_with_metadata` interceptor runs after the + `post_list_previews` interceptor. The (possibly modified) response returned by + `post_list_previews` will be passed to + `post_list_previews_with_metadata`. + """ + return response, metadata + + def pre_list_resource_changes(self, request: config.ListResourceChangesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[config.ListResourceChangesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_resource_changes + + Override in a subclass to manipulate the request or metadata + before they are sent to the Config server. + """ + return request, metadata + + def post_list_resource_changes(self, response: config.ListResourceChangesResponse) -> config.ListResourceChangesResponse: + """Post-rpc interceptor for list_resource_changes + + DEPRECATED. Please use the `post_list_resource_changes_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Config server but before + it is returned to user code. This `post_list_resource_changes` interceptor runs + before the `post_list_resource_changes_with_metadata` interceptor. + """ + return response + + def post_list_resource_changes_with_metadata(self, response: config.ListResourceChangesResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[config.ListResourceChangesResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for list_resource_changes + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Config server but before it is returned to user code. + + We recommend only using this `post_list_resource_changes_with_metadata` + interceptor in new development instead of the `post_list_resource_changes` interceptor. + When both interceptors are used, this `post_list_resource_changes_with_metadata` interceptor runs after the + `post_list_resource_changes` interceptor. The (possibly modified) response returned by + `post_list_resource_changes` will be passed to + `post_list_resource_changes_with_metadata`. + """ + return response, metadata + + def pre_list_resource_drifts(self, request: config.ListResourceDriftsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[config.ListResourceDriftsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_resource_drifts + + Override in a subclass to manipulate the request or metadata + before they are sent to the Config server. + """ + return request, metadata + + def post_list_resource_drifts(self, response: config.ListResourceDriftsResponse) -> config.ListResourceDriftsResponse: + """Post-rpc interceptor for list_resource_drifts + + DEPRECATED. Please use the `post_list_resource_drifts_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Config server but before + it is returned to user code. This `post_list_resource_drifts` interceptor runs + before the `post_list_resource_drifts_with_metadata` interceptor. + """ + return response + + def post_list_resource_drifts_with_metadata(self, response: config.ListResourceDriftsResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[config.ListResourceDriftsResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for list_resource_drifts + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Config server but before it is returned to user code. + + We recommend only using this `post_list_resource_drifts_with_metadata` + interceptor in new development instead of the `post_list_resource_drifts` interceptor. + When both interceptors are used, this `post_list_resource_drifts_with_metadata` interceptor runs after the + `post_list_resource_drifts` interceptor. The (possibly modified) response returned by + `post_list_resource_drifts` will be passed to + `post_list_resource_drifts_with_metadata`. + """ + return response, metadata + + def pre_list_resources(self, request: config.ListResourcesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[config.ListResourcesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_resources + + Override in a subclass to manipulate the request or metadata + before they are sent to the Config server. + """ + return request, metadata + + def post_list_resources(self, response: config.ListResourcesResponse) -> config.ListResourcesResponse: + """Post-rpc interceptor for list_resources + + DEPRECATED. Please use the `post_list_resources_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Config server but before + it is returned to user code. This `post_list_resources` interceptor runs + before the `post_list_resources_with_metadata` interceptor. + """ + return response + + def post_list_resources_with_metadata(self, response: config.ListResourcesResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[config.ListResourcesResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for list_resources + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Config server but before it is returned to user code. + + We recommend only using this `post_list_resources_with_metadata` + interceptor in new development instead of the `post_list_resources` interceptor. + When both interceptors are used, this `post_list_resources_with_metadata` interceptor runs after the + `post_list_resources` interceptor. The (possibly modified) response returned by + `post_list_resources` will be passed to + `post_list_resources_with_metadata`. + """ + return response, metadata + + def pre_list_revisions(self, request: config.ListRevisionsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[config.ListRevisionsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_revisions + + Override in a subclass to manipulate the request or metadata + before they are sent to the Config server. + """ + return request, metadata + + def post_list_revisions(self, response: config.ListRevisionsResponse) -> config.ListRevisionsResponse: + """Post-rpc interceptor for list_revisions + + DEPRECATED. Please use the `post_list_revisions_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Config server but before + it is returned to user code. This `post_list_revisions` interceptor runs + before the `post_list_revisions_with_metadata` interceptor. + """ + return response + + def post_list_revisions_with_metadata(self, response: config.ListRevisionsResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[config.ListRevisionsResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for list_revisions + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Config server but before it is returned to user code. + + We recommend only using this `post_list_revisions_with_metadata` + interceptor in new development instead of the `post_list_revisions` interceptor. + When both interceptors are used, this `post_list_revisions_with_metadata` interceptor runs after the + `post_list_revisions` interceptor. The (possibly modified) response returned by + `post_list_revisions` will be passed to + `post_list_revisions_with_metadata`. + """ + return response, metadata + + def pre_list_terraform_versions(self, request: config.ListTerraformVersionsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[config.ListTerraformVersionsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_terraform_versions + + Override in a subclass to manipulate the request or metadata + before they are sent to the Config server. + """ + return request, metadata + + def post_list_terraform_versions(self, response: config.ListTerraformVersionsResponse) -> config.ListTerraformVersionsResponse: + """Post-rpc interceptor for list_terraform_versions + + DEPRECATED. Please use the `post_list_terraform_versions_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Config server but before + it is returned to user code. This `post_list_terraform_versions` interceptor runs + before the `post_list_terraform_versions_with_metadata` interceptor. + """ + return response + + def post_list_terraform_versions_with_metadata(self, response: config.ListTerraformVersionsResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[config.ListTerraformVersionsResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for list_terraform_versions + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Config server but before it is returned to user code. + + We recommend only using this `post_list_terraform_versions_with_metadata` + interceptor in new development instead of the `post_list_terraform_versions` interceptor. + When both interceptors are used, this `post_list_terraform_versions_with_metadata` interceptor runs after the + `post_list_terraform_versions` interceptor. The (possibly modified) response returned by + `post_list_terraform_versions` will be passed to + `post_list_terraform_versions_with_metadata`. + """ + return response, metadata + + def pre_lock_deployment(self, request: config.LockDeploymentRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[config.LockDeploymentRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for lock_deployment + + Override in a subclass to manipulate the request or metadata + before they are sent to the Config server. + """ + return request, metadata + + def post_lock_deployment(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for lock_deployment + + DEPRECATED. Please use the `post_lock_deployment_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Config server but before + it is returned to user code. This `post_lock_deployment` interceptor runs + before the `post_lock_deployment_with_metadata` interceptor. + """ + return response + + def post_lock_deployment_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 lock_deployment + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Config server but before it is returned to user code. + + We recommend only using this `post_lock_deployment_with_metadata` + interceptor in new development instead of the `post_lock_deployment` interceptor. + When both interceptors are used, this `post_lock_deployment_with_metadata` interceptor runs after the + `post_lock_deployment` interceptor. The (possibly modified) response returned by + `post_lock_deployment` will be passed to + `post_lock_deployment_with_metadata`. + """ + return response, metadata + + def pre_unlock_deployment(self, request: config.UnlockDeploymentRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[config.UnlockDeploymentRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for unlock_deployment + + Override in a subclass to manipulate the request or metadata + before they are sent to the Config server. + """ + return request, metadata + + def post_unlock_deployment(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for unlock_deployment + + DEPRECATED. Please use the `post_unlock_deployment_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Config server but before + it is returned to user code. This `post_unlock_deployment` interceptor runs + before the `post_unlock_deployment_with_metadata` interceptor. + """ + return response + + def post_unlock_deployment_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 unlock_deployment + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Config server but before it is returned to user code. + + We recommend only using this `post_unlock_deployment_with_metadata` + interceptor in new development instead of the `post_unlock_deployment` interceptor. + When both interceptors are used, this `post_unlock_deployment_with_metadata` interceptor runs after the + `post_unlock_deployment` interceptor. The (possibly modified) response returned by + `post_unlock_deployment` will be passed to + `post_unlock_deployment_with_metadata`. + """ + return response, metadata + + def pre_update_deployment(self, request: config.UpdateDeploymentRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[config.UpdateDeploymentRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for update_deployment + + Override in a subclass to manipulate the request or metadata + before they are sent to the Config server. + """ + return request, metadata + + def post_update_deployment(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for update_deployment + + DEPRECATED. Please use the `post_update_deployment_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Config server but before + it is returned to user code. This `post_update_deployment` interceptor runs + before the `post_update_deployment_with_metadata` interceptor. + """ + return response + + def post_update_deployment_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_deployment + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Config server but before it is returned to user code. + + We recommend only using this `post_update_deployment_with_metadata` + interceptor in new development instead of the `post_update_deployment` interceptor. + When both interceptors are used, this `post_update_deployment_with_metadata` interceptor runs after the + `post_update_deployment` interceptor. The (possibly modified) response returned by + `post_update_deployment` will be passed to + `post_update_deployment_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 Config 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 Config 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 Config 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 Config 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 Config 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 Config 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 Config 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 Config 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 Config 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 Config 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 Config 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 Config 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 Config 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 Config 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 Config 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 Config 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 Config 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 Config server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class ConfigRestStub: + _session: AuthorizedSession + _host: str + _interceptor: ConfigRestInterceptor + + +class ConfigRestTransport(_BaseConfigRestTransport): + """REST backend synchronous transport for Config. + + Infrastructure Manager is a managed service that automates + the deployment and management of Google Cloud infrastructure + 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 = 'config.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[ConfigRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'config.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]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + 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. + """ + # 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 ConfigRestInterceptor() + 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': '/v1/{name=projects/*/locations/*/operations/*}:cancel', + 'body': '*', + }, + ], + 'google.longrunning.Operations.DeleteOperation': [ + { + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + }, + ], + 'google.longrunning.Operations.GetOperation': [ + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + }, + ], + 'google.longrunning.Operations.ListOperations': [ + { + 'method': 'get', + 'uri': '/v1/{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="v1") + + self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) + + # Return the client from cache. + return self._operations_client + + class _CreateDeployment(_BaseConfigRestTransport._BaseCreateDeployment, ConfigRestStub): + def __hash__(self): + return hash("ConfigRestTransport.CreateDeployment") + + @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: config.CreateDeploymentRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> operations_pb2.Operation: + r"""Call the create deployment method over HTTP. + + Args: + request (~.config.CreateDeploymentRequest): + The request 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`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseConfigRestTransport._BaseCreateDeployment._get_http_options() + + request, metadata = self._interceptor.pre_create_deployment(request, metadata) + transcoded_request = _BaseConfigRestTransport._BaseCreateDeployment._get_transcoded_request(http_options, request) + + body = _BaseConfigRestTransport._BaseCreateDeployment._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseConfigRestTransport._BaseCreateDeployment._get_query_params_json(transcoded_request) + + 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.config_v1.ConfigClient.CreateDeployment", + extra = { + "serviceName": "google.cloud.config.v1.Config", + "rpcName": "CreateDeployment", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ConfigRestTransport._CreateDeployment._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_deployment(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_deployment_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.config_v1.ConfigClient.create_deployment", + extra = { + "serviceName": "google.cloud.config.v1.Config", + "rpcName": "CreateDeployment", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CreatePreview(_BaseConfigRestTransport._BaseCreatePreview, ConfigRestStub): + def __hash__(self): + return hash("ConfigRestTransport.CreatePreview") + + @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: config.CreatePreviewRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> operations_pb2.Operation: + r"""Call the create preview method over HTTP. + + Args: + request (~.config.CreatePreviewRequest): + The request object. A request to create a preview. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each 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 = _BaseConfigRestTransport._BaseCreatePreview._get_http_options() + + request, metadata = self._interceptor.pre_create_preview(request, metadata) + transcoded_request = _BaseConfigRestTransport._BaseCreatePreview._get_transcoded_request(http_options, request) + + body = _BaseConfigRestTransport._BaseCreatePreview._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseConfigRestTransport._BaseCreatePreview._get_query_params_json(transcoded_request) + + 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.config_v1.ConfigClient.CreatePreview", + extra = { + "serviceName": "google.cloud.config.v1.Config", + "rpcName": "CreatePreview", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ConfigRestTransport._CreatePreview._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_preview(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_preview_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.config_v1.ConfigClient.create_preview", + extra = { + "serviceName": "google.cloud.config.v1.Config", + "rpcName": "CreatePreview", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteDeployment(_BaseConfigRestTransport._BaseDeleteDeployment, ConfigRestStub): + def __hash__(self): + return hash("ConfigRestTransport.DeleteDeployment") + + @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: config.DeleteDeploymentRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete deployment method over HTTP. + + Args: + request (~.config.DeleteDeploymentRequest): + The request 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`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseConfigRestTransport._BaseDeleteDeployment._get_http_options() + + request, metadata = self._interceptor.pre_delete_deployment(request, metadata) + transcoded_request = _BaseConfigRestTransport._BaseDeleteDeployment._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseConfigRestTransport._BaseDeleteDeployment._get_query_params_json(transcoded_request) + + 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.config_v1.ConfigClient.DeleteDeployment", + extra = { + "serviceName": "google.cloud.config.v1.Config", + "rpcName": "DeleteDeployment", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ConfigRestTransport._DeleteDeployment._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_deployment(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_delete_deployment_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.config_v1.ConfigClient.delete_deployment", + extra = { + "serviceName": "google.cloud.config.v1.Config", + "rpcName": "DeleteDeployment", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeletePreview(_BaseConfigRestTransport._BaseDeletePreview, ConfigRestStub): + def __hash__(self): + return hash("ConfigRestTransport.DeletePreview") + + @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: config.DeletePreviewRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete preview method over HTTP. + + Args: + request (~.config.DeletePreviewRequest): + The request object. A request to delete a preview. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each 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 = _BaseConfigRestTransport._BaseDeletePreview._get_http_options() + + request, metadata = self._interceptor.pre_delete_preview(request, metadata) + transcoded_request = _BaseConfigRestTransport._BaseDeletePreview._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseConfigRestTransport._BaseDeletePreview._get_query_params_json(transcoded_request) + + 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.config_v1.ConfigClient.DeletePreview", + extra = { + "serviceName": "google.cloud.config.v1.Config", + "rpcName": "DeletePreview", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ConfigRestTransport._DeletePreview._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_preview(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_delete_preview_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.config_v1.ConfigClient.delete_preview", + extra = { + "serviceName": "google.cloud.config.v1.Config", + "rpcName": "DeletePreview", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteStatefile(_BaseConfigRestTransport._BaseDeleteStatefile, ConfigRestStub): + def __hash__(self): + return hash("ConfigRestTransport.DeleteStatefile") + + @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: config.DeleteStatefileRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ): + r"""Call the delete statefile method over HTTP. + + Args: + request (~.config.DeleteStatefileRequest): + The request object. A request to delete a state file + passed to a 'DeleteStatefile' call. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, 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 = _BaseConfigRestTransport._BaseDeleteStatefile._get_http_options() + + request, metadata = self._interceptor.pre_delete_statefile(request, metadata) + transcoded_request = _BaseConfigRestTransport._BaseDeleteStatefile._get_transcoded_request(http_options, request) + + body = _BaseConfigRestTransport._BaseDeleteStatefile._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseConfigRestTransport._BaseDeleteStatefile._get_query_params_json(transcoded_request) + + 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.config_v1.ConfigClient.DeleteStatefile", + extra = { + "serviceName": "google.cloud.config.v1.Config", + "rpcName": "DeleteStatefile", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ConfigRestTransport._DeleteStatefile._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 _ExportDeploymentStatefile(_BaseConfigRestTransport._BaseExportDeploymentStatefile, ConfigRestStub): + def __hash__(self): + return hash("ConfigRestTransport.ExportDeploymentStatefile") + + @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: config.ExportDeploymentStatefileRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> config.Statefile: + r"""Call the export deployment + statefile method over HTTP. + + Args: + request (~.config.ExportDeploymentStatefileRequest): + The request object. A request to export a state file + passed to a 'ExportDeploymentStatefile' + call. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.config.Statefile: + Contains info about a Terraform state + file + + """ + + http_options = _BaseConfigRestTransport._BaseExportDeploymentStatefile._get_http_options() + + request, metadata = self._interceptor.pre_export_deployment_statefile(request, metadata) + transcoded_request = _BaseConfigRestTransport._BaseExportDeploymentStatefile._get_transcoded_request(http_options, request) + + body = _BaseConfigRestTransport._BaseExportDeploymentStatefile._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseConfigRestTransport._BaseExportDeploymentStatefile._get_query_params_json(transcoded_request) + + 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.config_v1.ConfigClient.ExportDeploymentStatefile", + extra = { + "serviceName": "google.cloud.config.v1.Config", + "rpcName": "ExportDeploymentStatefile", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ConfigRestTransport._ExportDeploymentStatefile._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 = config.Statefile() + pb_resp = config.Statefile.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_export_deployment_statefile(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_export_deployment_statefile_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = config.Statefile.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.config_v1.ConfigClient.export_deployment_statefile", + extra = { + "serviceName": "google.cloud.config.v1.Config", + "rpcName": "ExportDeploymentStatefile", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ExportLockInfo(_BaseConfigRestTransport._BaseExportLockInfo, ConfigRestStub): + def __hash__(self): + return hash("ConfigRestTransport.ExportLockInfo") + + @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: config.ExportLockInfoRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> config.LockInfo: + r"""Call the export lock info method over HTTP. + + Args: + request (~.config.ExportLockInfoRequest): + The request object. A request to get a state file lock + info passed to a 'ExportLockInfo' call. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.config.LockInfo: + Details about the lock which locked + the deployment. + + """ + + http_options = _BaseConfigRestTransport._BaseExportLockInfo._get_http_options() + + request, metadata = self._interceptor.pre_export_lock_info(request, metadata) + transcoded_request = _BaseConfigRestTransport._BaseExportLockInfo._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseConfigRestTransport._BaseExportLockInfo._get_query_params_json(transcoded_request) + + 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.config_v1.ConfigClient.ExportLockInfo", + extra = { + "serviceName": "google.cloud.config.v1.Config", + "rpcName": "ExportLockInfo", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ConfigRestTransport._ExportLockInfo._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 = config.LockInfo() + pb_resp = config.LockInfo.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_export_lock_info(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_export_lock_info_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = config.LockInfo.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.config_v1.ConfigClient.export_lock_info", + extra = { + "serviceName": "google.cloud.config.v1.Config", + "rpcName": "ExportLockInfo", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ExportPreviewResult(_BaseConfigRestTransport._BaseExportPreviewResult, ConfigRestStub): + def __hash__(self): + return hash("ConfigRestTransport.ExportPreviewResult") + + @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: config.ExportPreviewResultRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> config.ExportPreviewResultResponse: + r"""Call the export preview result method over HTTP. + + Args: + request (~.config.ExportPreviewResultRequest): + The request object. A request to export preview results. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.config.ExportPreviewResultResponse: + A response to ``ExportPreviewResult`` call. Contains + preview results. + + """ + + http_options = _BaseConfigRestTransport._BaseExportPreviewResult._get_http_options() + + request, metadata = self._interceptor.pre_export_preview_result(request, metadata) + transcoded_request = _BaseConfigRestTransport._BaseExportPreviewResult._get_transcoded_request(http_options, request) + + body = _BaseConfigRestTransport._BaseExportPreviewResult._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseConfigRestTransport._BaseExportPreviewResult._get_query_params_json(transcoded_request) + + 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.config_v1.ConfigClient.ExportPreviewResult", + extra = { + "serviceName": "google.cloud.config.v1.Config", + "rpcName": "ExportPreviewResult", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ConfigRestTransport._ExportPreviewResult._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 = config.ExportPreviewResultResponse() + pb_resp = config.ExportPreviewResultResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_export_preview_result(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_export_preview_result_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = config.ExportPreviewResultResponse.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.config_v1.ConfigClient.export_preview_result", + extra = { + "serviceName": "google.cloud.config.v1.Config", + "rpcName": "ExportPreviewResult", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ExportRevisionStatefile(_BaseConfigRestTransport._BaseExportRevisionStatefile, ConfigRestStub): + def __hash__(self): + return hash("ConfigRestTransport.ExportRevisionStatefile") + + @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: config.ExportRevisionStatefileRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> config.Statefile: + r"""Call the export revision statefile method over HTTP. + + Args: + request (~.config.ExportRevisionStatefileRequest): + The request object. A request to export a state file + passed to a 'ExportRevisionStatefile' + call. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.config.Statefile: + Contains info about a Terraform state + file + + """ + + http_options = _BaseConfigRestTransport._BaseExportRevisionStatefile._get_http_options() + + request, metadata = self._interceptor.pre_export_revision_statefile(request, metadata) + transcoded_request = _BaseConfigRestTransport._BaseExportRevisionStatefile._get_transcoded_request(http_options, request) + + body = _BaseConfigRestTransport._BaseExportRevisionStatefile._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseConfigRestTransport._BaseExportRevisionStatefile._get_query_params_json(transcoded_request) + + 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.config_v1.ConfigClient.ExportRevisionStatefile", + extra = { + "serviceName": "google.cloud.config.v1.Config", + "rpcName": "ExportRevisionStatefile", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ConfigRestTransport._ExportRevisionStatefile._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 = config.Statefile() + pb_resp = config.Statefile.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_export_revision_statefile(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_export_revision_statefile_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = config.Statefile.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.config_v1.ConfigClient.export_revision_statefile", + extra = { + "serviceName": "google.cloud.config.v1.Config", + "rpcName": "ExportRevisionStatefile", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetDeployment(_BaseConfigRestTransport._BaseGetDeployment, ConfigRestStub): + def __hash__(self): + return hash("ConfigRestTransport.GetDeployment") + + @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: config.GetDeploymentRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> config.Deployment: + r"""Call the get deployment method over HTTP. + + Args: + request (~.config.GetDeploymentRequest): + The request 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`. + + Returns: + ~.config.Deployment: + A Deployment is a group of resources + and configs managed and provisioned by + Infra Manager. + + """ + + http_options = _BaseConfigRestTransport._BaseGetDeployment._get_http_options() + + request, metadata = self._interceptor.pre_get_deployment(request, metadata) + transcoded_request = _BaseConfigRestTransport._BaseGetDeployment._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseConfigRestTransport._BaseGetDeployment._get_query_params_json(transcoded_request) + + 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.config_v1.ConfigClient.GetDeployment", + extra = { + "serviceName": "google.cloud.config.v1.Config", + "rpcName": "GetDeployment", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ConfigRestTransport._GetDeployment._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 = config.Deployment() + pb_resp = config.Deployment.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_deployment(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_deployment_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = config.Deployment.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.config_v1.ConfigClient.get_deployment", + extra = { + "serviceName": "google.cloud.config.v1.Config", + "rpcName": "GetDeployment", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetPreview(_BaseConfigRestTransport._BaseGetPreview, ConfigRestStub): + def __hash__(self): + return hash("ConfigRestTransport.GetPreview") + + @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: config.GetPreviewRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> config.Preview: + r"""Call the get preview method over HTTP. + + Args: + request (~.config.GetPreviewRequest): + The request object. A request to get details about a + preview. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.config.Preview: + A preview represents a set of actions + Infra Manager would perform to move the + resources towards the desired state as + specified in the configuration. + + """ + + http_options = _BaseConfigRestTransport._BaseGetPreview._get_http_options() + + request, metadata = self._interceptor.pre_get_preview(request, metadata) + transcoded_request = _BaseConfigRestTransport._BaseGetPreview._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseConfigRestTransport._BaseGetPreview._get_query_params_json(transcoded_request) + + 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.config_v1.ConfigClient.GetPreview", + extra = { + "serviceName": "google.cloud.config.v1.Config", + "rpcName": "GetPreview", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ConfigRestTransport._GetPreview._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 = config.Preview() + pb_resp = config.Preview.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_preview(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_preview_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = config.Preview.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.config_v1.ConfigClient.get_preview", + extra = { + "serviceName": "google.cloud.config.v1.Config", + "rpcName": "GetPreview", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetResource(_BaseConfigRestTransport._BaseGetResource, ConfigRestStub): + def __hash__(self): + return hash("ConfigRestTransport.GetResource") + + @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: config.GetResourceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> config.Resource: + r"""Call the get resource method over HTTP. + + Args: + request (~.config.GetResourceRequest): + The request object. A request to get a Resource from a + 'GetResource' call. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.config.Resource: + Resource represents a Google Cloud + Platform resource actuated by IM. + Resources are child resources of + Revisions. + + """ + + http_options = _BaseConfigRestTransport._BaseGetResource._get_http_options() + + request, metadata = self._interceptor.pre_get_resource(request, metadata) + transcoded_request = _BaseConfigRestTransport._BaseGetResource._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseConfigRestTransport._BaseGetResource._get_query_params_json(transcoded_request) + + 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.config_v1.ConfigClient.GetResource", + extra = { + "serviceName": "google.cloud.config.v1.Config", + "rpcName": "GetResource", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ConfigRestTransport._GetResource._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 = config.Resource() + pb_resp = config.Resource.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_resource(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_resource_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = config.Resource.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.config_v1.ConfigClient.get_resource", + extra = { + "serviceName": "google.cloud.config.v1.Config", + "rpcName": "GetResource", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetResourceChange(_BaseConfigRestTransport._BaseGetResourceChange, ConfigRestStub): + def __hash__(self): + return hash("ConfigRestTransport.GetResourceChange") + + @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: config.GetResourceChangeRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> config.ResourceChange: + r"""Call the get resource change method over HTTP. + + Args: + request (~.config.GetResourceChangeRequest): + The request object. The request message for the + GetResourceChange 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: + ~.config.ResourceChange: + A resource change represents a change + to a resource in the state file. + + """ + + http_options = _BaseConfigRestTransport._BaseGetResourceChange._get_http_options() + + request, metadata = self._interceptor.pre_get_resource_change(request, metadata) + transcoded_request = _BaseConfigRestTransport._BaseGetResourceChange._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseConfigRestTransport._BaseGetResourceChange._get_query_params_json(transcoded_request) + + 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.config_v1.ConfigClient.GetResourceChange", + extra = { + "serviceName": "google.cloud.config.v1.Config", + "rpcName": "GetResourceChange", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ConfigRestTransport._GetResourceChange._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 = config.ResourceChange() + pb_resp = config.ResourceChange.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_resource_change(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_resource_change_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = config.ResourceChange.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.config_v1.ConfigClient.get_resource_change", + extra = { + "serviceName": "google.cloud.config.v1.Config", + "rpcName": "GetResourceChange", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetResourceDrift(_BaseConfigRestTransport._BaseGetResourceDrift, ConfigRestStub): + def __hash__(self): + return hash("ConfigRestTransport.GetResourceDrift") + + @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: config.GetResourceDriftRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> config.ResourceDrift: + r"""Call the get resource drift method over HTTP. + + Args: + request (~.config.GetResourceDriftRequest): + The request object. The request message for the + GetResourceDrift 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: + ~.config.ResourceDrift: + A resource drift represents a drift + to a resource in the state file. + + """ + + http_options = _BaseConfigRestTransport._BaseGetResourceDrift._get_http_options() + + request, metadata = self._interceptor.pre_get_resource_drift(request, metadata) + transcoded_request = _BaseConfigRestTransport._BaseGetResourceDrift._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseConfigRestTransport._BaseGetResourceDrift._get_query_params_json(transcoded_request) + + 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.config_v1.ConfigClient.GetResourceDrift", + extra = { + "serviceName": "google.cloud.config.v1.Config", + "rpcName": "GetResourceDrift", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ConfigRestTransport._GetResourceDrift._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 = config.ResourceDrift() + pb_resp = config.ResourceDrift.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_resource_drift(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_resource_drift_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = config.ResourceDrift.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.config_v1.ConfigClient.get_resource_drift", + extra = { + "serviceName": "google.cloud.config.v1.Config", + "rpcName": "GetResourceDrift", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetRevision(_BaseConfigRestTransport._BaseGetRevision, ConfigRestStub): + def __hash__(self): + return hash("ConfigRestTransport.GetRevision") + + @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: config.GetRevisionRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> config.Revision: + r"""Call the get revision method over HTTP. + + Args: + request (~.config.GetRevisionRequest): + The request object. A request to get a Revision from a + 'GetRevision' call. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.config.Revision: + A child resource of a Deployment + generated by a 'CreateDeployment' or + 'UpdateDeployment' call. Each Revision + contains metadata pertaining to a + snapshot of a particular Deployment. + + """ + + http_options = _BaseConfigRestTransport._BaseGetRevision._get_http_options() + + request, metadata = self._interceptor.pre_get_revision(request, metadata) + transcoded_request = _BaseConfigRestTransport._BaseGetRevision._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseConfigRestTransport._BaseGetRevision._get_query_params_json(transcoded_request) + + 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.config_v1.ConfigClient.GetRevision", + extra = { + "serviceName": "google.cloud.config.v1.Config", + "rpcName": "GetRevision", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ConfigRestTransport._GetRevision._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 = config.Revision() + pb_resp = config.Revision.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_revision(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_revision_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = config.Revision.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.config_v1.ConfigClient.get_revision", + extra = { + "serviceName": "google.cloud.config.v1.Config", + "rpcName": "GetRevision", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetTerraformVersion(_BaseConfigRestTransport._BaseGetTerraformVersion, ConfigRestStub): + def __hash__(self): + return hash("ConfigRestTransport.GetTerraformVersion") + + @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: config.GetTerraformVersionRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> config.TerraformVersion: + r"""Call the get terraform version method over HTTP. + + Args: + request (~.config.GetTerraformVersionRequest): + The request object. The request message for the + GetTerraformVersion 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: + ~.config.TerraformVersion: + A TerraformVersion represents the + support state the corresponding + Terraform version. + + """ + + http_options = _BaseConfigRestTransport._BaseGetTerraformVersion._get_http_options() + + request, metadata = self._interceptor.pre_get_terraform_version(request, metadata) + transcoded_request = _BaseConfigRestTransport._BaseGetTerraformVersion._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseConfigRestTransport._BaseGetTerraformVersion._get_query_params_json(transcoded_request) + + 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.config_v1.ConfigClient.GetTerraformVersion", + extra = { + "serviceName": "google.cloud.config.v1.Config", + "rpcName": "GetTerraformVersion", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ConfigRestTransport._GetTerraformVersion._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 = config.TerraformVersion() + pb_resp = config.TerraformVersion.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_terraform_version(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_terraform_version_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = config.TerraformVersion.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.config_v1.ConfigClient.get_terraform_version", + extra = { + "serviceName": "google.cloud.config.v1.Config", + "rpcName": "GetTerraformVersion", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ImportStatefile(_BaseConfigRestTransport._BaseImportStatefile, ConfigRestStub): + def __hash__(self): + return hash("ConfigRestTransport.ImportStatefile") + + @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: config.ImportStatefileRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> config.Statefile: + r"""Call the import statefile method over HTTP. + + Args: + request (~.config.ImportStatefileRequest): + The request object. A request to import a state file + passed to a 'ImportStatefile' call. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.config.Statefile: + Contains info about a Terraform state + file + + """ + + http_options = _BaseConfigRestTransport._BaseImportStatefile._get_http_options() + + request, metadata = self._interceptor.pre_import_statefile(request, metadata) + transcoded_request = _BaseConfigRestTransport._BaseImportStatefile._get_transcoded_request(http_options, request) + + body = _BaseConfigRestTransport._BaseImportStatefile._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseConfigRestTransport._BaseImportStatefile._get_query_params_json(transcoded_request) + + 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.config_v1.ConfigClient.ImportStatefile", + extra = { + "serviceName": "google.cloud.config.v1.Config", + "rpcName": "ImportStatefile", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ConfigRestTransport._ImportStatefile._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 = config.Statefile() + pb_resp = config.Statefile.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_import_statefile(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_import_statefile_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = config.Statefile.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.config_v1.ConfigClient.import_statefile", + extra = { + "serviceName": "google.cloud.config.v1.Config", + "rpcName": "ImportStatefile", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListDeployments(_BaseConfigRestTransport._BaseListDeployments, ConfigRestStub): + def __hash__(self): + return hash("ConfigRestTransport.ListDeployments") + + @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: config.ListDeploymentsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> config.ListDeploymentsResponse: + r"""Call the list deployments method over HTTP. + + Args: + request (~.config.ListDeploymentsRequest): + The request 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`. + + Returns: + ~.config.ListDeploymentsResponse: + + """ + + http_options = _BaseConfigRestTransport._BaseListDeployments._get_http_options() + + request, metadata = self._interceptor.pre_list_deployments(request, metadata) + transcoded_request = _BaseConfigRestTransport._BaseListDeployments._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseConfigRestTransport._BaseListDeployments._get_query_params_json(transcoded_request) + + 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.config_v1.ConfigClient.ListDeployments", + extra = { + "serviceName": "google.cloud.config.v1.Config", + "rpcName": "ListDeployments", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ConfigRestTransport._ListDeployments._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 = config.ListDeploymentsResponse() + pb_resp = config.ListDeploymentsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_deployments(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_deployments_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = config.ListDeploymentsResponse.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.config_v1.ConfigClient.list_deployments", + extra = { + "serviceName": "google.cloud.config.v1.Config", + "rpcName": "ListDeployments", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListPreviews(_BaseConfigRestTransport._BaseListPreviews, ConfigRestStub): + def __hash__(self): + return hash("ConfigRestTransport.ListPreviews") + + @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: config.ListPreviewsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> config.ListPreviewsResponse: + r"""Call the list previews method over HTTP. + + Args: + request (~.config.ListPreviewsRequest): + The request object. A request to list all previews for a + given project and location. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.config.ListPreviewsResponse: + A response to a ``ListPreviews`` call. Contains a list + of Previews. + + """ + + http_options = _BaseConfigRestTransport._BaseListPreviews._get_http_options() + + request, metadata = self._interceptor.pre_list_previews(request, metadata) + transcoded_request = _BaseConfigRestTransport._BaseListPreviews._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseConfigRestTransport._BaseListPreviews._get_query_params_json(transcoded_request) + + 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.config_v1.ConfigClient.ListPreviews", + extra = { + "serviceName": "google.cloud.config.v1.Config", + "rpcName": "ListPreviews", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ConfigRestTransport._ListPreviews._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 = config.ListPreviewsResponse() + pb_resp = config.ListPreviewsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_previews(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_previews_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = config.ListPreviewsResponse.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.config_v1.ConfigClient.list_previews", + extra = { + "serviceName": "google.cloud.config.v1.Config", + "rpcName": "ListPreviews", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListResourceChanges(_BaseConfigRestTransport._BaseListResourceChanges, ConfigRestStub): + def __hash__(self): + return hash("ConfigRestTransport.ListResourceChanges") + + @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: config.ListResourceChangesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> config.ListResourceChangesResponse: + r"""Call the list resource changes method over HTTP. + + Args: + request (~.config.ListResourceChangesRequest): + The request object. The request message for the + ListResourceChanges 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: + ~.config.ListResourceChangesResponse: + A response to a 'ListResourceChanges' + call. Contains a list of + ResourceChanges. + + """ + + http_options = _BaseConfigRestTransport._BaseListResourceChanges._get_http_options() + + request, metadata = self._interceptor.pre_list_resource_changes(request, metadata) + transcoded_request = _BaseConfigRestTransport._BaseListResourceChanges._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseConfigRestTransport._BaseListResourceChanges._get_query_params_json(transcoded_request) + + 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.config_v1.ConfigClient.ListResourceChanges", + extra = { + "serviceName": "google.cloud.config.v1.Config", + "rpcName": "ListResourceChanges", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ConfigRestTransport._ListResourceChanges._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 = config.ListResourceChangesResponse() + pb_resp = config.ListResourceChangesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_resource_changes(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_resource_changes_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = config.ListResourceChangesResponse.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.config_v1.ConfigClient.list_resource_changes", + extra = { + "serviceName": "google.cloud.config.v1.Config", + "rpcName": "ListResourceChanges", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListResourceDrifts(_BaseConfigRestTransport._BaseListResourceDrifts, ConfigRestStub): + def __hash__(self): + return hash("ConfigRestTransport.ListResourceDrifts") + + @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: config.ListResourceDriftsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> config.ListResourceDriftsResponse: + r"""Call the list resource drifts method over HTTP. + + Args: + request (~.config.ListResourceDriftsRequest): + The request object. The request message for the + ListResourceDrifts 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: + ~.config.ListResourceDriftsResponse: + A response to a 'ListResourceDrifts' + call. Contains a list of ResourceDrifts. + + """ + + http_options = _BaseConfigRestTransport._BaseListResourceDrifts._get_http_options() + + request, metadata = self._interceptor.pre_list_resource_drifts(request, metadata) + transcoded_request = _BaseConfigRestTransport._BaseListResourceDrifts._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseConfigRestTransport._BaseListResourceDrifts._get_query_params_json(transcoded_request) + + 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.config_v1.ConfigClient.ListResourceDrifts", + extra = { + "serviceName": "google.cloud.config.v1.Config", + "rpcName": "ListResourceDrifts", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ConfigRestTransport._ListResourceDrifts._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 = config.ListResourceDriftsResponse() + pb_resp = config.ListResourceDriftsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_resource_drifts(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_resource_drifts_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = config.ListResourceDriftsResponse.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.config_v1.ConfigClient.list_resource_drifts", + extra = { + "serviceName": "google.cloud.config.v1.Config", + "rpcName": "ListResourceDrifts", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListResources(_BaseConfigRestTransport._BaseListResources, ConfigRestStub): + def __hash__(self): + return hash("ConfigRestTransport.ListResources") + + @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: config.ListResourcesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> config.ListResourcesResponse: + r"""Call the list resources method over HTTP. + + Args: + request (~.config.ListResourcesRequest): + The request object. A request to list Resources passed to + a 'ListResources' call. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.config.ListResourcesResponse: + A response to a 'ListResources' call. + Contains a list of Resources. + + """ + + http_options = _BaseConfigRestTransport._BaseListResources._get_http_options() + + request, metadata = self._interceptor.pre_list_resources(request, metadata) + transcoded_request = _BaseConfigRestTransport._BaseListResources._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseConfigRestTransport._BaseListResources._get_query_params_json(transcoded_request) + + 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.config_v1.ConfigClient.ListResources", + extra = { + "serviceName": "google.cloud.config.v1.Config", + "rpcName": "ListResources", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ConfigRestTransport._ListResources._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 = config.ListResourcesResponse() + pb_resp = config.ListResourcesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_resources(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_resources_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = config.ListResourcesResponse.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.config_v1.ConfigClient.list_resources", + extra = { + "serviceName": "google.cloud.config.v1.Config", + "rpcName": "ListResources", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListRevisions(_BaseConfigRestTransport._BaseListRevisions, ConfigRestStub): + def __hash__(self): + return hash("ConfigRestTransport.ListRevisions") + + @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: config.ListRevisionsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> config.ListRevisionsResponse: + r"""Call the list revisions method over HTTP. + + Args: + request (~.config.ListRevisionsRequest): + The request object. A request to list Revisions passed to + a 'ListRevisions' call. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.config.ListRevisionsResponse: + A response to a 'ListRevisions' call. + Contains a list of Revisions. + + """ + + http_options = _BaseConfigRestTransport._BaseListRevisions._get_http_options() + + request, metadata = self._interceptor.pre_list_revisions(request, metadata) + transcoded_request = _BaseConfigRestTransport._BaseListRevisions._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseConfigRestTransport._BaseListRevisions._get_query_params_json(transcoded_request) + + 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.config_v1.ConfigClient.ListRevisions", + extra = { + "serviceName": "google.cloud.config.v1.Config", + "rpcName": "ListRevisions", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ConfigRestTransport._ListRevisions._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 = config.ListRevisionsResponse() + pb_resp = config.ListRevisionsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_revisions(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_revisions_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = config.ListRevisionsResponse.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.config_v1.ConfigClient.list_revisions", + extra = { + "serviceName": "google.cloud.config.v1.Config", + "rpcName": "ListRevisions", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListTerraformVersions(_BaseConfigRestTransport._BaseListTerraformVersions, ConfigRestStub): + def __hash__(self): + return hash("ConfigRestTransport.ListTerraformVersions") + + @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: config.ListTerraformVersionsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> config.ListTerraformVersionsResponse: + r"""Call the list terraform versions method over HTTP. + + Args: + request (~.config.ListTerraformVersionsRequest): + The request object. The request message for the + ListTerraformVersions 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: + ~.config.ListTerraformVersionsResponse: + The response message for the ``ListTerraformVersions`` + method. + + """ + + http_options = _BaseConfigRestTransport._BaseListTerraformVersions._get_http_options() + + request, metadata = self._interceptor.pre_list_terraform_versions(request, metadata) + transcoded_request = _BaseConfigRestTransport._BaseListTerraformVersions._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseConfigRestTransport._BaseListTerraformVersions._get_query_params_json(transcoded_request) + + 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.config_v1.ConfigClient.ListTerraformVersions", + extra = { + "serviceName": "google.cloud.config.v1.Config", + "rpcName": "ListTerraformVersions", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ConfigRestTransport._ListTerraformVersions._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 = config.ListTerraformVersionsResponse() + pb_resp = config.ListTerraformVersionsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_terraform_versions(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_terraform_versions_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER + try: + response_payload = config.ListTerraformVersionsResponse.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.config_v1.ConfigClient.list_terraform_versions", + extra = { + "serviceName": "google.cloud.config.v1.Config", + "rpcName": "ListTerraformVersions", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _LockDeployment(_BaseConfigRestTransport._BaseLockDeployment, ConfigRestStub): + def __hash__(self): + return hash("ConfigRestTransport.LockDeployment") + + @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: config.LockDeploymentRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> operations_pb2.Operation: + r"""Call the lock deployment method over HTTP. + + Args: + request (~.config.LockDeploymentRequest): + The request object. A request to lock a deployment passed + to a 'LockDeployment' call. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each 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 = _BaseConfigRestTransport._BaseLockDeployment._get_http_options() + + request, metadata = self._interceptor.pre_lock_deployment(request, metadata) + transcoded_request = _BaseConfigRestTransport._BaseLockDeployment._get_transcoded_request(http_options, request) + + body = _BaseConfigRestTransport._BaseLockDeployment._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseConfigRestTransport._BaseLockDeployment._get_query_params_json(transcoded_request) + + 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.config_v1.ConfigClient.LockDeployment", + extra = { + "serviceName": "google.cloud.config.v1.Config", + "rpcName": "LockDeployment", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ConfigRestTransport._LockDeployment._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_lock_deployment(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_lock_deployment_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.config_v1.ConfigClient.lock_deployment", + extra = { + "serviceName": "google.cloud.config.v1.Config", + "rpcName": "LockDeployment", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UnlockDeployment(_BaseConfigRestTransport._BaseUnlockDeployment, ConfigRestStub): + def __hash__(self): + return hash("ConfigRestTransport.UnlockDeployment") + + @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: config.UnlockDeploymentRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> operations_pb2.Operation: + r"""Call the unlock deployment method over HTTP. + + Args: + request (~.config.UnlockDeploymentRequest): + The request object. A request to unlock a state file + passed to a 'UnlockDeployment' call. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each 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 = _BaseConfigRestTransport._BaseUnlockDeployment._get_http_options() + + request, metadata = self._interceptor.pre_unlock_deployment(request, metadata) + transcoded_request = _BaseConfigRestTransport._BaseUnlockDeployment._get_transcoded_request(http_options, request) + + body = _BaseConfigRestTransport._BaseUnlockDeployment._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseConfigRestTransport._BaseUnlockDeployment._get_query_params_json(transcoded_request) + + 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.config_v1.ConfigClient.UnlockDeployment", + extra = { + "serviceName": "google.cloud.config.v1.Config", + "rpcName": "UnlockDeployment", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ConfigRestTransport._UnlockDeployment._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_unlock_deployment(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_unlock_deployment_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.config_v1.ConfigClient.unlock_deployment", + extra = { + "serviceName": "google.cloud.config.v1.Config", + "rpcName": "UnlockDeployment", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateDeployment(_BaseConfigRestTransport._BaseUpdateDeployment, ConfigRestStub): + def __hash__(self): + return hash("ConfigRestTransport.UpdateDeployment") + + @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: config.UpdateDeploymentRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), + ) -> operations_pb2.Operation: + r"""Call the update deployment method over HTTP. + + Args: + request (~.config.UpdateDeploymentRequest): + The request 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`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseConfigRestTransport._BaseUpdateDeployment._get_http_options() + + request, metadata = self._interceptor.pre_update_deployment(request, metadata) + transcoded_request = _BaseConfigRestTransport._BaseUpdateDeployment._get_transcoded_request(http_options, request) + + body = _BaseConfigRestTransport._BaseUpdateDeployment._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseConfigRestTransport._BaseUpdateDeployment._get_query_params_json(transcoded_request) + + 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.config_v1.ConfigClient.UpdateDeployment", + extra = { + "serviceName": "google.cloud.config.v1.Config", + "rpcName": "UpdateDeployment", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ConfigRestTransport._UpdateDeployment._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_deployment(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_deployment_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.config_v1.ConfigClient.update_deployment", + extra = { + "serviceName": "google.cloud.config.v1.Config", + "rpcName": "UpdateDeployment", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def create_deployment(self) -> Callable[ + [config.CreateDeploymentRequest], + 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._CreateDeployment(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_preview(self) -> Callable[ + [config.CreatePreviewRequest], + 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._CreatePreview(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_deployment(self) -> Callable[ + [config.DeleteDeploymentRequest], + 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._DeleteDeployment(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_preview(self) -> Callable[ + [config.DeletePreviewRequest], + 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._DeletePreview(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_statefile(self) -> Callable[ + [config.DeleteStatefileRequest], + 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._DeleteStatefile(self._session, self._host, self._interceptor) # type: ignore + + @property + def export_deployment_statefile(self) -> Callable[ + [config.ExportDeploymentStatefileRequest], + config.Statefile]: + # 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._ExportDeploymentStatefile(self._session, self._host, self._interceptor) # type: ignore + + @property + def export_lock_info(self) -> Callable[ + [config.ExportLockInfoRequest], + config.LockInfo]: + # 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._ExportLockInfo(self._session, self._host, self._interceptor) # type: ignore + + @property + def export_preview_result(self) -> Callable[ + [config.ExportPreviewResultRequest], + config.ExportPreviewResultResponse]: + # 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._ExportPreviewResult(self._session, self._host, self._interceptor) # type: ignore + + @property + def export_revision_statefile(self) -> Callable[ + [config.ExportRevisionStatefileRequest], + config.Statefile]: + # 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._ExportRevisionStatefile(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_deployment(self) -> Callable[ + [config.GetDeploymentRequest], + config.Deployment]: + # 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._GetDeployment(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_preview(self) -> Callable[ + [config.GetPreviewRequest], + config.Preview]: + # 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._GetPreview(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_resource(self) -> Callable[ + [config.GetResourceRequest], + config.Resource]: + # 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._GetResource(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_resource_change(self) -> Callable[ + [config.GetResourceChangeRequest], + config.ResourceChange]: + # 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._GetResourceChange(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_resource_drift(self) -> Callable[ + [config.GetResourceDriftRequest], + config.ResourceDrift]: + # 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._GetResourceDrift(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_revision(self) -> Callable[ + [config.GetRevisionRequest], + config.Revision]: + # 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._GetRevision(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_terraform_version(self) -> Callable[ + [config.GetTerraformVersionRequest], + config.TerraformVersion]: + # 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._GetTerraformVersion(self._session, self._host, self._interceptor) # type: ignore + + @property + def import_statefile(self) -> Callable[ + [config.ImportStatefileRequest], + config.Statefile]: + # 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._ImportStatefile(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_deployments(self) -> Callable[ + [config.ListDeploymentsRequest], + config.ListDeploymentsResponse]: + # 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._ListDeployments(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_previews(self) -> Callable[ + [config.ListPreviewsRequest], + config.ListPreviewsResponse]: + # 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._ListPreviews(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_resource_changes(self) -> Callable[ + [config.ListResourceChangesRequest], + config.ListResourceChangesResponse]: + # 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._ListResourceChanges(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_resource_drifts(self) -> Callable[ + [config.ListResourceDriftsRequest], + config.ListResourceDriftsResponse]: + # 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._ListResourceDrifts(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_resources(self) -> Callable[ + [config.ListResourcesRequest], + config.ListResourcesResponse]: + # 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._ListResources(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_revisions(self) -> Callable[ + [config.ListRevisionsRequest], + config.ListRevisionsResponse]: + # 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._ListRevisions(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_terraform_versions(self) -> Callable[ + [config.ListTerraformVersionsRequest], + config.ListTerraformVersionsResponse]: + # 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._ListTerraformVersions(self._session, self._host, self._interceptor) # type: ignore + + @property + def lock_deployment(self) -> Callable[ + [config.LockDeploymentRequest], + 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._LockDeployment(self._session, self._host, self._interceptor) # type: ignore + + @property + def unlock_deployment(self) -> Callable[ + [config.UnlockDeploymentRequest], + 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._UnlockDeployment(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_deployment(self) -> Callable[ + [config.UpdateDeploymentRequest], + 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._UpdateDeployment(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(_BaseConfigRestTransport._BaseGetLocation, ConfigRestStub): + def __hash__(self): + return hash("ConfigRestTransport.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 = _BaseConfigRestTransport._BaseGetLocation._get_http_options() + + request, metadata = self._interceptor.pre_get_location(request, metadata) + transcoded_request = _BaseConfigRestTransport._BaseGetLocation._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseConfigRestTransport._BaseGetLocation._get_query_params_json(transcoded_request) + + 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.config_v1.ConfigClient.GetLocation", + extra = { + "serviceName": "google.cloud.config.v1.Config", + "rpcName": "GetLocation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ConfigRestTransport._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.config_v1.ConfigAsyncClient.GetLocation", + extra = { + "serviceName": "google.cloud.config.v1.Config", + "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(_BaseConfigRestTransport._BaseListLocations, ConfigRestStub): + def __hash__(self): + return hash("ConfigRestTransport.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 = _BaseConfigRestTransport._BaseListLocations._get_http_options() + + request, metadata = self._interceptor.pre_list_locations(request, metadata) + transcoded_request = _BaseConfigRestTransport._BaseListLocations._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseConfigRestTransport._BaseListLocations._get_query_params_json(transcoded_request) + + 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.config_v1.ConfigClient.ListLocations", + extra = { + "serviceName": "google.cloud.config.v1.Config", + "rpcName": "ListLocations", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ConfigRestTransport._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.config_v1.ConfigAsyncClient.ListLocations", + extra = { + "serviceName": "google.cloud.config.v1.Config", + "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(_BaseConfigRestTransport._BaseGetIamPolicy, ConfigRestStub): + def __hash__(self): + return hash("ConfigRestTransport.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 = _BaseConfigRestTransport._BaseGetIamPolicy._get_http_options() + + request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) + transcoded_request = _BaseConfigRestTransport._BaseGetIamPolicy._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseConfigRestTransport._BaseGetIamPolicy._get_query_params_json(transcoded_request) + + 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.config_v1.ConfigClient.GetIamPolicy", + extra = { + "serviceName": "google.cloud.config.v1.Config", + "rpcName": "GetIamPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ConfigRestTransport._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.config_v1.ConfigAsyncClient.GetIamPolicy", + extra = { + "serviceName": "google.cloud.config.v1.Config", + "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(_BaseConfigRestTransport._BaseSetIamPolicy, ConfigRestStub): + def __hash__(self): + return hash("ConfigRestTransport.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 = _BaseConfigRestTransport._BaseSetIamPolicy._get_http_options() + + request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) + transcoded_request = _BaseConfigRestTransport._BaseSetIamPolicy._get_transcoded_request(http_options, request) + + body = _BaseConfigRestTransport._BaseSetIamPolicy._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseConfigRestTransport._BaseSetIamPolicy._get_query_params_json(transcoded_request) + + 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.config_v1.ConfigClient.SetIamPolicy", + extra = { + "serviceName": "google.cloud.config.v1.Config", + "rpcName": "SetIamPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ConfigRestTransport._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.config_v1.ConfigAsyncClient.SetIamPolicy", + extra = { + "serviceName": "google.cloud.config.v1.Config", + "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(_BaseConfigRestTransport._BaseTestIamPermissions, ConfigRestStub): + def __hash__(self): + return hash("ConfigRestTransport.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 = _BaseConfigRestTransport._BaseTestIamPermissions._get_http_options() + + request, metadata = self._interceptor.pre_test_iam_permissions(request, metadata) + transcoded_request = _BaseConfigRestTransport._BaseTestIamPermissions._get_transcoded_request(http_options, request) + + body = _BaseConfigRestTransport._BaseTestIamPermissions._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseConfigRestTransport._BaseTestIamPermissions._get_query_params_json(transcoded_request) + + 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.config_v1.ConfigClient.TestIamPermissions", + extra = { + "serviceName": "google.cloud.config.v1.Config", + "rpcName": "TestIamPermissions", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ConfigRestTransport._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.config_v1.ConfigAsyncClient.TestIamPermissions", + extra = { + "serviceName": "google.cloud.config.v1.Config", + "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(_BaseConfigRestTransport._BaseCancelOperation, ConfigRestStub): + def __hash__(self): + return hash("ConfigRestTransport.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 = _BaseConfigRestTransport._BaseCancelOperation._get_http_options() + + request, metadata = self._interceptor.pre_cancel_operation(request, metadata) + transcoded_request = _BaseConfigRestTransport._BaseCancelOperation._get_transcoded_request(http_options, request) + + body = _BaseConfigRestTransport._BaseCancelOperation._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseConfigRestTransport._BaseCancelOperation._get_query_params_json(transcoded_request) + + 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.config_v1.ConfigClient.CancelOperation", + extra = { + "serviceName": "google.cloud.config.v1.Config", + "rpcName": "CancelOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ConfigRestTransport._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(_BaseConfigRestTransport._BaseDeleteOperation, ConfigRestStub): + def __hash__(self): + return hash("ConfigRestTransport.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 = _BaseConfigRestTransport._BaseDeleteOperation._get_http_options() + + request, metadata = self._interceptor.pre_delete_operation(request, metadata) + transcoded_request = _BaseConfigRestTransport._BaseDeleteOperation._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseConfigRestTransport._BaseDeleteOperation._get_query_params_json(transcoded_request) + + 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.config_v1.ConfigClient.DeleteOperation", + extra = { + "serviceName": "google.cloud.config.v1.Config", + "rpcName": "DeleteOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ConfigRestTransport._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(_BaseConfigRestTransport._BaseGetOperation, ConfigRestStub): + def __hash__(self): + return hash("ConfigRestTransport.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 = _BaseConfigRestTransport._BaseGetOperation._get_http_options() + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + transcoded_request = _BaseConfigRestTransport._BaseGetOperation._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseConfigRestTransport._BaseGetOperation._get_query_params_json(transcoded_request) + + 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.config_v1.ConfigClient.GetOperation", + extra = { + "serviceName": "google.cloud.config.v1.Config", + "rpcName": "GetOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ConfigRestTransport._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.config_v1.ConfigAsyncClient.GetOperation", + extra = { + "serviceName": "google.cloud.config.v1.Config", + "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(_BaseConfigRestTransport._BaseListOperations, ConfigRestStub): + def __hash__(self): + return hash("ConfigRestTransport.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 = _BaseConfigRestTransport._BaseListOperations._get_http_options() + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + transcoded_request = _BaseConfigRestTransport._BaseListOperations._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseConfigRestTransport._BaseListOperations._get_query_params_json(transcoded_request) + + 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.config_v1.ConfigClient.ListOperations", + extra = { + "serviceName": "google.cloud.config.v1.Config", + "rpcName": "ListOperations", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ConfigRestTransport._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.config_v1.ConfigAsyncClient.ListOperations", + extra = { + "serviceName": "google.cloud.config.v1.Config", + "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__=( + 'ConfigRestTransport', +) diff --git a/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/transports/rest_base.py b/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/transports/rest_base.py new file mode 100644 index 000000000000..08824caf9058 --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/transports/rest_base.py @@ -0,0 +1,1435 @@ +# -*- 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. +# +import json # type: ignore +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from .base import ConfigTransport, DEFAULT_CLIENT_INFO + +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + + +from google.cloud.config_v1.types import config +from google.protobuf import empty_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + + +class _BaseConfigRestTransport(ConfigTransport): + """Base REST backend transport for Config. + + 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 = 'config.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: 'config.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 _BaseCreateDeployment: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "deploymentId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*}/deployments', + 'body': 'deployment', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = config.CreateDeploymentRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseConfigRestTransport._BaseCreateDeployment._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreatePreview: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*}/previews', + 'body': 'preview', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = config.CreatePreviewRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseConfigRestTransport._BaseCreatePreview._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteDeployment: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/deployments/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = config.DeleteDeploymentRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseConfigRestTransport._BaseDeleteDeployment._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeletePreview: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/previews/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = config.DeletePreviewRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseConfigRestTransport._BaseDeletePreview._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteStatefile: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{name=projects/*/locations/*/deployments/*}:deleteState', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = config.DeleteStatefileRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseConfigRestTransport._BaseDeleteStatefile._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseExportDeploymentStatefile: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*/deployments/*}:exportState', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = config.ExportDeploymentStatefileRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseConfigRestTransport._BaseExportDeploymentStatefile._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseExportLockInfo: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/deployments/*}:exportLock', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = config.ExportLockInfoRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseConfigRestTransport._BaseExportLockInfo._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseExportPreviewResult: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*/previews/*}:export', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = config.ExportPreviewResultRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseConfigRestTransport._BaseExportPreviewResult._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseExportRevisionStatefile: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*/deployments/*/revisions/*}:exportState', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = config.ExportRevisionStatefileRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseConfigRestTransport._BaseExportRevisionStatefile._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetDeployment: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/deployments/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = config.GetDeploymentRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseConfigRestTransport._BaseGetDeployment._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetPreview: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/previews/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = config.GetPreviewRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseConfigRestTransport._BaseGetPreview._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetResource: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/deployments/*/revisions/*/resources/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = config.GetResourceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseConfigRestTransport._BaseGetResource._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetResourceChange: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/previews/*/resourceChanges/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = config.GetResourceChangeRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseConfigRestTransport._BaseGetResourceChange._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetResourceDrift: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/previews/*/resourceDrifts/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = config.GetResourceDriftRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseConfigRestTransport._BaseGetResourceDrift._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetRevision: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/deployments/*/revisions/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = config.GetRevisionRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseConfigRestTransport._BaseGetRevision._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetTerraformVersion: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/terraformVersions/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = config.GetTerraformVersionRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseConfigRestTransport._BaseGetTerraformVersion._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseImportStatefile: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*/deployments/*}:importState', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = config.ImportStatefileRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseConfigRestTransport._BaseImportStatefile._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListDeployments: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*}/deployments', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = config.ListDeploymentsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseConfigRestTransport._BaseListDeployments._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListPreviews: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*}/previews', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = config.ListPreviewsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseConfigRestTransport._BaseListPreviews._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListResourceChanges: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*/previews/*}/resourceChanges', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = config.ListResourceChangesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseConfigRestTransport._BaseListResourceChanges._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListResourceDrifts: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*/previews/*}/resourceDrifts', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = config.ListResourceDriftsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseConfigRestTransport._BaseListResourceDrifts._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListResources: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*/deployments/*/revisions/*}/resources', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = config.ListResourcesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseConfigRestTransport._BaseListResources._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListRevisions: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*/deployments/*}/revisions', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = config.ListRevisionsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseConfigRestTransport._BaseListRevisions._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListTerraformVersions: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*}/terraformVersions', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = config.ListTerraformVersionsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseConfigRestTransport._BaseListTerraformVersions._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseLockDeployment: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{name=projects/*/locations/*/deployments/*}:lock', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = config.LockDeploymentRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseConfigRestTransport._BaseLockDeployment._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUnlockDeployment: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{name=projects/*/locations/*/deployments/*}:unlock', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = config.UnlockDeploymentRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseConfigRestTransport._BaseUnlockDeployment._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateDeployment: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{deployment.name=projects/*/locations/*/deployments/*}', + 'body': 'deployment', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = config.UpdateDeploymentRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseConfigRestTransport._BaseUpdateDeployment._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + 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': '/v1/{name=projects/*/locations/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + return query_params + + 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': '/v1/{name=projects/*}/locations', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + return query_params + + 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': '/v1/{resource=projects/*/locations/*/deployments/*}:getIamPolicy', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + return query_params + + 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': '/v1/{resource=projects/*/locations/*/deployments/*}:setIamPolicy', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + body = json.dumps(transcoded_request['body']) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + return query_params + + 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': '/v1/{resource=projects/*/locations/*/deployments/*}:testIamPermissions', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + body = json.dumps(transcoded_request['body']) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + return query_params + + 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=projects/*/locations/*/operations/*}:cancel', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + body = json.dumps(transcoded_request['body']) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + return query_params + + 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': '/v1/{name=projects/*/locations/*/operations/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + return query_params + + 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=projects/*/locations/*/operations/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + return query_params + + 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': '/v1/{name=projects/*/locations/*}/operations', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + return query_params + + +__all__=( + '_BaseConfigRestTransport', +) diff --git a/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/types/__init__.py b/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/types/__init__.py new file mode 100644 index 000000000000..a569bc7349ae --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/types/__init__.py @@ -0,0 +1,146 @@ +# -*- 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. +# +from .config import ( + ApplyResults, + CreateDeploymentRequest, + CreatePreviewRequest, + DeleteDeploymentRequest, + DeletePreviewRequest, + DeleteStatefileRequest, + Deployment, + DeploymentOperationMetadata, + ExportDeploymentStatefileRequest, + ExportLockInfoRequest, + ExportPreviewResultRequest, + ExportPreviewResultResponse, + ExportRevisionStatefileRequest, + GetDeploymentRequest, + GetPreviewRequest, + GetResourceChangeRequest, + GetResourceDriftRequest, + GetResourceRequest, + GetRevisionRequest, + GetTerraformVersionRequest, + GitSource, + ImportStatefileRequest, + ListDeploymentsRequest, + ListDeploymentsResponse, + ListPreviewsRequest, + ListPreviewsResponse, + ListResourceChangesRequest, + ListResourceChangesResponse, + ListResourceDriftsRequest, + ListResourceDriftsResponse, + ListResourcesRequest, + ListResourcesResponse, + ListRevisionsRequest, + ListRevisionsResponse, + ListTerraformVersionsRequest, + ListTerraformVersionsResponse, + LockDeploymentRequest, + LockInfo, + OperationMetadata, + Preview, + PreviewArtifacts, + PreviewOperationMetadata, + PreviewResult, + PropertyChange, + PropertyDrift, + ProviderConfig, + Resource, + ResourceCAIInfo, + ResourceChange, + ResourceChangeTerraformInfo, + ResourceDrift, + ResourceDriftTerraformInfo, + ResourceTerraformInfo, + Revision, + Statefile, + TerraformBlueprint, + TerraformError, + TerraformOutput, + TerraformVariable, + TerraformVersion, + UnlockDeploymentRequest, + UpdateDeploymentRequest, + QuotaValidation, +) + +__all__ = ( + 'ApplyResults', + 'CreateDeploymentRequest', + 'CreatePreviewRequest', + 'DeleteDeploymentRequest', + 'DeletePreviewRequest', + 'DeleteStatefileRequest', + 'Deployment', + 'DeploymentOperationMetadata', + 'ExportDeploymentStatefileRequest', + 'ExportLockInfoRequest', + 'ExportPreviewResultRequest', + 'ExportPreviewResultResponse', + 'ExportRevisionStatefileRequest', + 'GetDeploymentRequest', + 'GetPreviewRequest', + 'GetResourceChangeRequest', + 'GetResourceDriftRequest', + 'GetResourceRequest', + 'GetRevisionRequest', + 'GetTerraformVersionRequest', + 'GitSource', + 'ImportStatefileRequest', + 'ListDeploymentsRequest', + 'ListDeploymentsResponse', + 'ListPreviewsRequest', + 'ListPreviewsResponse', + 'ListResourceChangesRequest', + 'ListResourceChangesResponse', + 'ListResourceDriftsRequest', + 'ListResourceDriftsResponse', + 'ListResourcesRequest', + 'ListResourcesResponse', + 'ListRevisionsRequest', + 'ListRevisionsResponse', + 'ListTerraformVersionsRequest', + 'ListTerraformVersionsResponse', + 'LockDeploymentRequest', + 'LockInfo', + 'OperationMetadata', + 'Preview', + 'PreviewArtifacts', + 'PreviewOperationMetadata', + 'PreviewResult', + 'PropertyChange', + 'PropertyDrift', + 'ProviderConfig', + 'Resource', + 'ResourceCAIInfo', + 'ResourceChange', + 'ResourceChangeTerraformInfo', + 'ResourceDrift', + 'ResourceDriftTerraformInfo', + 'ResourceTerraformInfo', + 'Revision', + 'Statefile', + 'TerraformBlueprint', + 'TerraformError', + 'TerraformOutput', + 'TerraformVariable', + 'TerraformVersion', + 'UnlockDeploymentRequest', + 'UpdateDeploymentRequest', + 'QuotaValidation', +) diff --git a/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/types/config.py b/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/types/config.py new file mode 100644 index 000000000000..b46aae6d4ca4 --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/types/config.py @@ -0,0 +1,3309 @@ +# -*- 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. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.config.v1', + manifest={ + 'QuotaValidation', + 'Deployment', + 'TerraformBlueprint', + 'TerraformVariable', + 'ApplyResults', + 'TerraformOutput', + 'ListDeploymentsRequest', + 'ListDeploymentsResponse', + 'GetDeploymentRequest', + 'ListRevisionsRequest', + 'ListRevisionsResponse', + 'GetRevisionRequest', + 'CreateDeploymentRequest', + 'UpdateDeploymentRequest', + 'DeleteDeploymentRequest', + 'OperationMetadata', + 'Revision', + 'TerraformError', + 'GitSource', + 'DeploymentOperationMetadata', + 'Resource', + 'ResourceTerraformInfo', + 'ResourceCAIInfo', + 'GetResourceRequest', + 'ListResourcesRequest', + 'ListResourcesResponse', + 'Statefile', + 'ExportDeploymentStatefileRequest', + 'ExportRevisionStatefileRequest', + 'ImportStatefileRequest', + 'DeleteStatefileRequest', + 'LockDeploymentRequest', + 'UnlockDeploymentRequest', + 'ExportLockInfoRequest', + 'LockInfo', + 'Preview', + 'PreviewOperationMetadata', + 'PreviewArtifacts', + 'CreatePreviewRequest', + 'GetPreviewRequest', + 'ListPreviewsRequest', + 'ListPreviewsResponse', + 'DeletePreviewRequest', + 'ExportPreviewResultRequest', + 'ExportPreviewResultResponse', + 'PreviewResult', + 'GetTerraformVersionRequest', + 'ListTerraformVersionsRequest', + 'ListTerraformVersionsResponse', + 'TerraformVersion', + 'ResourceChangeTerraformInfo', + 'ResourceChange', + 'PropertyChange', + 'ListResourceChangesRequest', + 'ListResourceChangesResponse', + 'GetResourceChangeRequest', + 'ResourceDriftTerraformInfo', + 'ResourceDrift', + 'PropertyDrift', + 'ListResourceDriftsRequest', + 'ListResourceDriftsResponse', + 'GetResourceDriftRequest', + 'ProviderConfig', + }, +) + + +class QuotaValidation(proto.Enum): + r"""Enum values to control quota checks for resources in + terraform configuration files. + + Values: + QUOTA_VALIDATION_UNSPECIFIED (0): + The default value. + QuotaValidation on terraform configuration files + will be disabled in this case. + ENABLED (1): + Enable computing quotas for resources in + terraform configuration files to get visibility + on resources with insufficient quotas. + ENFORCED (2): + Enforce quota checks so deployment fails if + there isn't sufficient quotas available to + deploy resources in terraform configuration + files. + """ + QUOTA_VALIDATION_UNSPECIFIED = 0 + ENABLED = 1 + ENFORCED = 2 + + +class Deployment(proto.Message): + r"""A Deployment is a group of resources and configs managed and + provisioned by Infra Manager. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + terraform_blueprint (google.cloud.config_v1.types.TerraformBlueprint): + A blueprint described using Terraform's + HashiCorp Configuration Language as a root + module. + + This field is a member of `oneof`_ ``blueprint``. + name (str): + Identifier. Resource name of the deployment. Format: + ``projects/{project}/locations/{location}/deployments/{deployment}`` + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time when the deployment was + created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time when the deployment was + last modified. + labels (MutableMapping[str, str]): + Optional. User-defined metadata for the + deployment. + state (google.cloud.config_v1.types.Deployment.State): + Output only. Current state of the deployment. + latest_revision (str): + Output only. Revision name that was most recently applied. + Format: + ``projects/{project}/locations/{location}/deployments/{deployment}/ revisions/{revision}`` + state_detail (str): + Output only. Additional information regarding + the current state. + error_code (google.cloud.config_v1.types.Deployment.ErrorCode): + Output only. Error code describing errors + that may have occurred. + delete_results (google.cloud.config_v1.types.ApplyResults): + Output only. Location of artifacts from a + DeleteDeployment operation. + delete_build (str): + Output only. Cloud Build instance UUID + associated with deleting this deployment. + delete_logs (str): + Output only. Location of Cloud Build logs in Google Cloud + Storage, populated when deleting this deployment. Format: + ``gs://{bucket}/{object}``. + tf_errors (MutableSequence[google.cloud.config_v1.types.TerraformError]): + Output only. Errors encountered when deleting this + deployment. Errors are truncated to 10 entries, see + ``delete_results`` and ``error_logs`` for full details. + error_logs (str): + Output only. Location of Terraform error logs in Google + Cloud Storage. Format: ``gs://{bucket}/{object}``. + artifacts_gcs_bucket (str): + Optional. User-defined location of Cloud Build logs and + artifacts in Google Cloud Storage. Format: + ``gs://{bucket}/{folder}`` + + A default bucket will be bootstrapped if the field is not + set or empty. Default bucket format: + ``gs://--blueprint-config`` + Constraints: + + - The bucket needs to be in the same project as the + deployment + - The path cannot be within the path of ``gcs_source`` + - The field cannot be updated, including changing its + presence + + This field is a member of `oneof`_ ``_artifacts_gcs_bucket``. + service_account (str): + Required. User-specified Service Account (SA) credentials to + be used when actuating resources. Format: + ``projects/{projectID}/serviceAccounts/{serviceAccount}`` + + This field is a member of `oneof`_ ``_service_account``. + import_existing_resources (bool): + By default, Infra Manager will return a + failure when Terraform encounters a 409 code + (resource conflict error) during actuation. If + this flag is set to true, Infra Manager will + instead attempt to automatically import the + resource into the Terraform state (for supported + resource types) and continue actuation. + + Not all resource types are supported, refer to + documentation. + + This field is a member of `oneof`_ ``_import_existing_resources``. + worker_pool (str): + Optional. The user-specified Cloud Build worker pool + resource in which the Cloud Build job will execute. Format: + ``projects/{project}/locations/{location}/workerPools/{workerPoolId}``. + If this field is unspecified, the default Cloud Build worker + pool will be used. + + This field is a member of `oneof`_ ``_worker_pool``. + lock_state (google.cloud.config_v1.types.Deployment.LockState): + Output only. Current lock state of the + deployment. + tf_version_constraint (str): + Optional. The user-specified Terraform + version constraint. Example: "=1.3.10". + + This field is a member of `oneof`_ ``_tf_version_constraint``. + tf_version (str): + Output only. The current Terraform version + set on the deployment. It is in the format of + "Major.Minor.Patch", for example, "1.3.10". + quota_validation (google.cloud.config_v1.types.QuotaValidation): + Optional. Input to control quota checks for + resources in terraform configuration files. + There are limited resources on which quota + validation applies. + annotations (MutableMapping[str, str]): + Optional. Arbitrary key-value metadata + storage e.g. to help client tools identify + deployments during automation. See + https://google.aip.dev/148#annotations for + details on format and size limitations. + provider_config (google.cloud.config_v1.types.ProviderConfig): + Optional. This field specifies the provider + configurations. + """ + class State(proto.Enum): + r"""Possible states of a deployment. + + Values: + STATE_UNSPECIFIED (0): + The default value. This value is used if the + state is omitted. + CREATING (1): + The deployment is being created. + ACTIVE (2): + The deployment is healthy. + UPDATING (3): + The deployment is being updated. + DELETING (4): + The deployment is being deleted. + FAILED (5): + The deployment has encountered an unexpected + error. + SUSPENDED (6): + The deployment is no longer being actively + reconciled. This may be the result of recovering + the project after deletion. + DELETED (7): + The deployment has been deleted. + """ + STATE_UNSPECIFIED = 0 + CREATING = 1 + ACTIVE = 2 + UPDATING = 3 + DELETING = 4 + FAILED = 5 + SUSPENDED = 6 + DELETED = 7 + + class ErrorCode(proto.Enum): + r"""Possible errors that can occur with deployments. + + Values: + ERROR_CODE_UNSPECIFIED (0): + No error code was specified. + REVISION_FAILED (1): + The revision failed. See Revision for more + details. + CLOUD_BUILD_PERMISSION_DENIED (3): + Cloud Build failed due to a permission issue. + DELETE_BUILD_API_FAILED (5): + Cloud Build job associated with a deployment + deletion could not be started. + DELETE_BUILD_RUN_FAILED (6): + Cloud Build job associated with a deployment + deletion was started but failed. + BUCKET_CREATION_PERMISSION_DENIED (7): + Cloud Storage bucket creation failed due to a + permission issue. + BUCKET_CREATION_FAILED (8): + Cloud Storage bucket creation failed due to + an issue unrelated to permissions. + """ + ERROR_CODE_UNSPECIFIED = 0 + REVISION_FAILED = 1 + CLOUD_BUILD_PERMISSION_DENIED = 3 + DELETE_BUILD_API_FAILED = 5 + DELETE_BUILD_RUN_FAILED = 6 + BUCKET_CREATION_PERMISSION_DENIED = 7 + BUCKET_CREATION_FAILED = 8 + + class LockState(proto.Enum): + r"""Possible lock states of a deployment. + + Values: + LOCK_STATE_UNSPECIFIED (0): + The default value. This value is used if the + lock state is omitted. + LOCKED (1): + The deployment is locked. + UNLOCKED (2): + The deployment is unlocked. + LOCKING (3): + The deployment is being locked. + UNLOCKING (4): + The deployment is being unlocked. + LOCK_FAILED (5): + The deployment has failed to lock. + UNLOCK_FAILED (6): + The deployment has failed to unlock. + """ + LOCK_STATE_UNSPECIFIED = 0 + LOCKED = 1 + UNLOCKED = 2 + LOCKING = 3 + UNLOCKING = 4 + LOCK_FAILED = 5 + UNLOCK_FAILED = 6 + + terraform_blueprint: 'TerraformBlueprint' = proto.Field( + proto.MESSAGE, + number=6, + oneof='blueprint', + message='TerraformBlueprint', + ) + 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, + ) + state: State = proto.Field( + proto.ENUM, + number=5, + enum=State, + ) + latest_revision: str = proto.Field( + proto.STRING, + number=7, + ) + state_detail: str = proto.Field( + proto.STRING, + number=9, + ) + error_code: ErrorCode = proto.Field( + proto.ENUM, + number=10, + enum=ErrorCode, + ) + delete_results: 'ApplyResults' = proto.Field( + proto.MESSAGE, + number=8, + message='ApplyResults', + ) + delete_build: str = proto.Field( + proto.STRING, + number=11, + ) + delete_logs: str = proto.Field( + proto.STRING, + number=12, + ) + tf_errors: MutableSequence['TerraformError'] = proto.RepeatedField( + proto.MESSAGE, + number=13, + message='TerraformError', + ) + error_logs: str = proto.Field( + proto.STRING, + number=14, + ) + artifacts_gcs_bucket: str = proto.Field( + proto.STRING, + number=15, + optional=True, + ) + service_account: str = proto.Field( + proto.STRING, + number=16, + optional=True, + ) + import_existing_resources: bool = proto.Field( + proto.BOOL, + number=17, + optional=True, + ) + worker_pool: str = proto.Field( + proto.STRING, + number=19, + optional=True, + ) + lock_state: LockState = proto.Field( + proto.ENUM, + number=20, + enum=LockState, + ) + tf_version_constraint: str = proto.Field( + proto.STRING, + number=21, + optional=True, + ) + tf_version: str = proto.Field( + proto.STRING, + number=22, + ) + quota_validation: 'QuotaValidation' = proto.Field( + proto.ENUM, + number=23, + enum='QuotaValidation', + ) + annotations: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=24, + ) + provider_config: 'ProviderConfig' = proto.Field( + proto.MESSAGE, + number=25, + message='ProviderConfig', + ) + + +class TerraformBlueprint(proto.Message): + r"""TerraformBlueprint describes the source of a Terraform root + module which describes the resources and configs to be deployed. + + 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: + gcs_source (str): + URI of an object in Google Cloud Storage. Format: + ``gs://{bucket}/{object}`` + + URI may also specify an object version for zipped objects. + Format: ``gs://{bucket}/{object}#{version}`` + + This field is a member of `oneof`_ ``source``. + git_source (google.cloud.config_v1.types.GitSource): + URI of a public Git repo. + + This field is a member of `oneof`_ ``source``. + input_values (MutableMapping[str, google.cloud.config_v1.types.TerraformVariable]): + Optional. Input variable values for the + Terraform blueprint. + """ + + gcs_source: str = proto.Field( + proto.STRING, + number=1, + oneof='source', + ) + git_source: 'GitSource' = proto.Field( + proto.MESSAGE, + number=2, + oneof='source', + message='GitSource', + ) + input_values: MutableMapping[str, 'TerraformVariable'] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=4, + message='TerraformVariable', + ) + + +class TerraformVariable(proto.Message): + r"""A Terraform input variable. + + Attributes: + input_value (google.protobuf.struct_pb2.Value): + Optional. Input variable value. + """ + + input_value: struct_pb2.Value = proto.Field( + proto.MESSAGE, + number=5, + message=struct_pb2.Value, + ) + + +class ApplyResults(proto.Message): + r"""Outputs and artifacts from applying a deployment. + + Attributes: + content (str): + Location of a blueprint copy and other manifests in Google + Cloud Storage. Format: ``gs://{bucket}/{object}`` + artifacts (str): + Location of artifacts (e.g. logs) in Google Cloud Storage. + Format: ``gs://{bucket}/{object}`` + outputs (MutableMapping[str, google.cloud.config_v1.types.TerraformOutput]): + Map of output name to output info. + """ + + content: str = proto.Field( + proto.STRING, + number=1, + ) + artifacts: str = proto.Field( + proto.STRING, + number=2, + ) + outputs: MutableMapping[str, 'TerraformOutput'] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=3, + message='TerraformOutput', + ) + + +class TerraformOutput(proto.Message): + r"""Describes a Terraform output. + + Attributes: + sensitive (bool): + Identifies whether Terraform has set this + output as a potential sensitive value. + value (google.protobuf.struct_pb2.Value): + Value of output. + """ + + sensitive: bool = proto.Field( + proto.BOOL, + number=1, + ) + value: struct_pb2.Value = proto.Field( + proto.MESSAGE, + number=2, + message=struct_pb2.Value, + ) + + +class ListDeploymentsRequest(proto.Message): + r""" + + Attributes: + parent (str): + Required. The parent in whose context the Deployments are + listed. The parent value is in the format: + 'projects/{project_id}/locations/{location}'. + page_size (int): + When requesting a page of resources, 'page_size' specifies + number of resources to return. If unspecified, at most 500 + will be returned. The maximum value is 1000. + page_token (str): + Token returned by previous call to + 'ListDeployments' which specifies the position + in the list from where to continue listing the + resources. + filter (str): + Lists the Deployments that match the filter expression. A + filter expression filters the resources listed in the + response. The expression must be of the form '{field} + {operator} {value}' where operators: '<', '>', '<=', '>=', + '!=', '=', ':' are supported (colon ':' represents a HAS + operator which is roughly synonymous with equality). {field} + can refer to a proto or JSON field, or a synthetic field. + Field names can be camelCase or snake_case. + + Examples: + + - Filter by name: name = + "projects/foo/locations/us-central1/deployments/bar + + - Filter by labels: + + - Resources that have a key called 'foo' labels.foo:\* + - Resources that have a key called 'foo' whose value is + 'bar' labels.foo = bar + + - Filter by state: + + - Deployments in CREATING state. state=CREATING + order_by (str): + Field to use to sort the list. + """ + + 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 ListDeploymentsResponse(proto.Message): + r""" + + Attributes: + deployments (MutableSequence[google.cloud.config_v1.types.Deployment]): + List of [Deployment][google.cloud.config.v1.Deployment]s. + next_page_token (str): + Token to be supplied to the next ListDeployments request via + ``page_token`` to obtain the next set of results. + unreachable (MutableSequence[str]): + Locations that could not be reached. + """ + + @property + def raw_page(self): + return self + + deployments: MutableSequence['Deployment'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Deployment', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class GetDeploymentRequest(proto.Message): + r""" + + Attributes: + name (str): + Required. The name of the deployment. Format: + 'projects/{project_id}/locations/{location}/deployments/{deployment}'. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListRevisionsRequest(proto.Message): + r"""A request to list Revisions passed to a 'ListRevisions' call. + + Attributes: + parent (str): + Required. The parent in whose context the Revisions are + listed. The parent value is in the format: + 'projects/{project_id}/locations/{location}/deployments/{deployment}'. + page_size (int): + When requesting a page of resources, ``page_size`` specifies + number of resources to return. If unspecified, at most 500 + will be returned. The maximum value is 1000. + page_token (str): + Token returned by previous call to + 'ListRevisions' which specifies the position in + the list from where to continue listing the + resources. + filter (str): + Lists the Revisions that match the filter expression. A + filter expression filters the resources listed in the + response. The expression must be of the form '{field} + {operator} {value}' where operators: '<', '>', '<=', '>=', + '!=', '=', ':' are supported (colon ':' represents a HAS + operator which is roughly synonymous with equality). {field} + can refer to a proto or JSON field, or a synthetic field. + Field names can be camelCase or snake_case. + + Examples: + + - Filter by name: name = + "projects/foo/locations/us-central1/deployments/dep/revisions/bar + + - Filter by labels: + + - Resources that have a key called 'foo' labels.foo:\* + - Resources that have a key called 'foo' whose value is + 'bar' labels.foo = bar + + - Filter by state: + + - Revisions in CREATING state. state=CREATING + order_by (str): + Field to use to sort the list. + """ + + 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 ListRevisionsResponse(proto.Message): + r"""A response to a 'ListRevisions' call. Contains a list of + Revisions. + + Attributes: + revisions (MutableSequence[google.cloud.config_v1.types.Revision]): + List of [Revision][google.cloud.config.v1.Revision]s. + next_page_token (str): + A token to request the next page of resources + from the 'ListRevisions' method. The value of an + empty string means that there are no more + resources to return. + unreachable (MutableSequence[str]): + Locations that could not be reached. + """ + + @property + def raw_page(self): + return self + + revisions: MutableSequence['Revision'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Revision', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class GetRevisionRequest(proto.Message): + r"""A request to get a Revision from a 'GetRevision' call. + + Attributes: + name (str): + Required. The name of the Revision in the format: + 'projects/{project_id}/locations/{location}/deployments/{deployment}/revisions/{revision}'. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateDeploymentRequest(proto.Message): + r""" + + Attributes: + parent (str): + Required. The parent in whose context the Deployment is + created. The parent value is in the format: + 'projects/{project_id}/locations/{location}'. + deployment_id (str): + Required. The Deployment ID. + deployment (google.cloud.config_v1.types.Deployment): + Required. [Deployment][google.cloud.config.v1.Deployment] + 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 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, + ) + deployment_id: str = proto.Field( + proto.STRING, + number=2, + ) + deployment: 'Deployment' = proto.Field( + proto.MESSAGE, + number=3, + message='Deployment', + ) + request_id: str = proto.Field( + proto.STRING, + number=4, + ) + + +class UpdateDeploymentRequest(proto.Message): + r""" + + Attributes: + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask used to specify the fields to be + overwritten in the Deployment 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. + deployment (google.cloud.config_v1.types.Deployment): + Required. [Deployment][google.cloud.config.v1.Deployment] to + update. + + The deployment's ``name`` field is used to identify the + resource to be updated. Format: + ``projects/{project}/locations/{location}/deployments/{deployment}`` + 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, + ) + deployment: 'Deployment' = proto.Field( + proto.MESSAGE, + number=2, + message='Deployment', + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class DeleteDeploymentRequest(proto.Message): + r""" + + Attributes: + name (str): + Required. The name of the Deployment in the format: + 'projects/{project_id}/locations/{location}/deployments/{deployment}'. + 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 revisions for + this deployment will also be deleted. + (Otherwise, the request will only work if the + deployment has no revisions.) + delete_policy (google.cloud.config_v1.types.DeleteDeploymentRequest.DeletePolicy): + Optional. Policy on how resources actuated by + the deployment should be deleted. If + unspecified, the default behavior is to delete + the underlying resources. + """ + class DeletePolicy(proto.Enum): + r"""Policy on how resources actuated by the deployment should be + deleted. + + Values: + DELETE_POLICY_UNSPECIFIED (0): + Unspecified policy, resources will be + deleted. + DELETE (1): + Deletes resources actuated by the deployment. + ABANDON (2): + Abandons resources and only deletes the + deployment and its metadata. + """ + DELETE_POLICY_UNSPECIFIED = 0 + DELETE = 1 + ABANDON = 2 + + 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, + ) + delete_policy: DeletePolicy = proto.Field( + proto.ENUM, + number=4, + enum=DeletePolicy, + ) + + +class OperationMetadata(proto.Message): + r"""Represents the metadata of the long-running operation. + + 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: + deployment_metadata (google.cloud.config_v1.types.DeploymentOperationMetadata): + Output only. Metadata about the deployment + operation state. + + This field is a member of `oneof`_ ``resource_metadata``. + preview_metadata (google.cloud.config_v1.types.PreviewOperationMetadata): + Output only. Metadata about the preview + operation state. + + This field is a member of `oneof`_ ``resource_metadata``. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time when the operation was + created. + end_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time when 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. + """ + + deployment_metadata: 'DeploymentOperationMetadata' = proto.Field( + proto.MESSAGE, + number=8, + oneof='resource_metadata', + message='DeploymentOperationMetadata', + ) + preview_metadata: 'PreviewOperationMetadata' = proto.Field( + proto.MESSAGE, + number=9, + oneof='resource_metadata', + message='PreviewOperationMetadata', + ) + 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 Revision(proto.Message): + r"""A child resource of a Deployment generated by a + 'CreateDeployment' or 'UpdateDeployment' call. Each Revision + contains metadata pertaining to a snapshot of a particular + Deployment. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + terraform_blueprint (google.cloud.config_v1.types.TerraformBlueprint): + Output only. A blueprint described using + Terraform's HashiCorp Configuration Language as + a root module. + + This field is a member of `oneof`_ ``blueprint``. + name (str): + Revision name. Format: + ``projects/{project}/locations/{location}/deployments/{deployment}/ revisions/{revision}`` + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time when the revision was + created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time when the revision was last + modified. + action (google.cloud.config_v1.types.Revision.Action): + Output only. The action which created this + revision + state (google.cloud.config_v1.types.Revision.State): + Output only. Current state of the revision. + apply_results (google.cloud.config_v1.types.ApplyResults): + Output only. Outputs and artifacts from + applying a deployment. + state_detail (str): + Output only. Additional info regarding the + current state. + error_code (google.cloud.config_v1.types.Revision.ErrorCode): + Output only. Code describing any errors that + may have occurred. + build (str): + Output only. Cloud Build instance UUID + associated with this revision. + logs (str): + Output only. Location of Revision operation logs in + ``gs://{bucket}/{object}`` format. + tf_errors (MutableSequence[google.cloud.config_v1.types.TerraformError]): + Output only. Errors encountered when creating or updating + this deployment. Errors are truncated to 10 entries, see + ``delete_results`` and ``error_logs`` for full details. + error_logs (str): + Output only. Location of Terraform error logs in Google + Cloud Storage. Format: ``gs://{bucket}/{object}``. + service_account (str): + Output only. User-specified Service Account (SA) to be used + as credential to manage resources. Format: + ``projects/{projectID}/serviceAccounts/{serviceAccount}`` + import_existing_resources (bool): + Output only. By default, Infra Manager will + return a failure when Terraform encounters a 409 + code (resource conflict error) during actuation. + If this flag is set to true, Infra Manager will + instead attempt to automatically import the + resource into the Terraform state (for supported + resource types) and continue actuation. + + Not all resource types are supported, refer to + documentation. + worker_pool (str): + Output only. The user-specified Cloud Build worker pool + resource in which the Cloud Build job will execute. Format: + ``projects/{project}/locations/{location}/workerPools/{workerPoolId}``. + If this field is unspecified, the default Cloud Build worker + pool will be used. + tf_version_constraint (str): + Output only. The user-specified Terraform + version constraint. Example: "=1.3.10". + tf_version (str): + Output only. The version of Terraform used to + create the Revision. It is in the format of + "Major.Minor.Patch", for example, "1.3.10". + quota_validation_results (str): + Output only. Cloud Storage path containing quota validation + results. This field is set when a user sets + Deployment.quota_validation field to ENABLED or ENFORCED. + Format: ``gs://{bucket}/{object}``. + quota_validation (google.cloud.config_v1.types.QuotaValidation): + Optional. Input to control quota checks for + resources in terraform configuration files. + There are limited resources on which quota + validation applies. + provider_config (google.cloud.config_v1.types.ProviderConfig): + Output only. This field specifies the + provider configurations. + """ + class Action(proto.Enum): + r"""Actions that generate a revision. + + Values: + ACTION_UNSPECIFIED (0): + The default value. This value is used if the + action is omitted. + CREATE (1): + The revision was generated by creating a + deployment. + UPDATE (2): + The revision was generated by updating a + deployment. + DELETE (3): + The revision was deleted. + """ + ACTION_UNSPECIFIED = 0 + CREATE = 1 + UPDATE = 2 + DELETE = 3 + + class State(proto.Enum): + r"""Possible states of a revision. + + Values: + STATE_UNSPECIFIED (0): + The default value. This value is used if the + state is omitted. + APPLYING (1): + The revision is being applied. + APPLIED (2): + The revision was applied successfully. + FAILED (3): + The revision could not be applied + successfully. + """ + STATE_UNSPECIFIED = 0 + APPLYING = 1 + APPLIED = 2 + FAILED = 3 + + class ErrorCode(proto.Enum): + r"""Possible errors if Revision could not be created or updated + successfully. + + Values: + ERROR_CODE_UNSPECIFIED (0): + No error code was specified. + CLOUD_BUILD_PERMISSION_DENIED (1): + Cloud Build failed due to a permission issue. + APPLY_BUILD_API_FAILED (4): + Cloud Build job associated with creating or + updating a deployment could not be started. + APPLY_BUILD_RUN_FAILED (5): + Cloud Build job associated with creating or + updating a deployment was started but failed. + QUOTA_VALIDATION_FAILED (7): + quota validation failed for one or more + resources in terraform configuration files. + """ + ERROR_CODE_UNSPECIFIED = 0 + CLOUD_BUILD_PERMISSION_DENIED = 1 + APPLY_BUILD_API_FAILED = 4 + APPLY_BUILD_RUN_FAILED = 5 + QUOTA_VALIDATION_FAILED = 7 + + terraform_blueprint: 'TerraformBlueprint' = proto.Field( + proto.MESSAGE, + number=6, + oneof='blueprint', + message='TerraformBlueprint', + ) + 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, + ) + action: Action = proto.Field( + proto.ENUM, + number=4, + enum=Action, + ) + state: State = proto.Field( + proto.ENUM, + number=5, + enum=State, + ) + apply_results: 'ApplyResults' = proto.Field( + proto.MESSAGE, + number=7, + message='ApplyResults', + ) + state_detail: str = proto.Field( + proto.STRING, + number=8, + ) + error_code: ErrorCode = proto.Field( + proto.ENUM, + number=9, + enum=ErrorCode, + ) + build: str = proto.Field( + proto.STRING, + number=10, + ) + logs: str = proto.Field( + proto.STRING, + number=11, + ) + tf_errors: MutableSequence['TerraformError'] = proto.RepeatedField( + proto.MESSAGE, + number=12, + message='TerraformError', + ) + error_logs: str = proto.Field( + proto.STRING, + number=13, + ) + service_account: str = proto.Field( + proto.STRING, + number=14, + ) + import_existing_resources: bool = proto.Field( + proto.BOOL, + number=15, + ) + worker_pool: str = proto.Field( + proto.STRING, + number=17, + ) + tf_version_constraint: str = proto.Field( + proto.STRING, + number=18, + ) + tf_version: str = proto.Field( + proto.STRING, + number=19, + ) + quota_validation_results: str = proto.Field( + proto.STRING, + number=29, + ) + quota_validation: 'QuotaValidation' = proto.Field( + proto.ENUM, + number=20, + enum='QuotaValidation', + ) + provider_config: 'ProviderConfig' = proto.Field( + proto.MESSAGE, + number=21, + message='ProviderConfig', + ) + + +class TerraformError(proto.Message): + r"""Errors encountered during actuation using Terraform + + Attributes: + resource_address (str): + Address of the resource associated with the error, e.g. + ``google_compute_network.vpc_network``. + http_response_code (int): + HTTP response code returned from Google Cloud + Platform APIs when Terraform fails to provision + the resource. If unset or 0, no HTTP response + code was returned by Terraform. + error_description (str): + A human-readable error description. + error (google.rpc.status_pb2.Status): + Output only. Original error response from + underlying Google API, if available. + """ + + resource_address: str = proto.Field( + proto.STRING, + number=1, + ) + http_response_code: int = proto.Field( + proto.INT32, + number=2, + ) + error_description: str = proto.Field( + proto.STRING, + number=3, + ) + error: status_pb2.Status = proto.Field( + proto.MESSAGE, + number=4, + message=status_pb2.Status, + ) + + +class GitSource(proto.Message): + r"""A set of files in a Git repository. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + repo (str): + Optional. Repository URL. + Example: + 'https://github.com/kubernetes/examples.git' + + This field is a member of `oneof`_ ``_repo``. + directory (str): + Optional. Subdirectory inside the repository. + Example: 'staging/my-package' + + This field is a member of `oneof`_ ``_directory``. + ref (str): + Optional. Git reference (e.g. branch or tag). + + This field is a member of `oneof`_ ``_ref``. + """ + + repo: str = proto.Field( + proto.STRING, + number=1, + optional=True, + ) + directory: str = proto.Field( + proto.STRING, + number=2, + optional=True, + ) + ref: str = proto.Field( + proto.STRING, + number=3, + optional=True, + ) + + +class DeploymentOperationMetadata(proto.Message): + r"""Ephemeral metadata content describing the state of a + deployment operation. + + Attributes: + step (google.cloud.config_v1.types.DeploymentOperationMetadata.DeploymentStep): + The current step the deployment operation is + running. + apply_results (google.cloud.config_v1.types.ApplyResults): + Outputs and artifacts from applying a + deployment. + build (str): + Output only. Cloud Build instance UUID + associated with this operation. + logs (str): + Output only. Location of Deployment operations logs in + ``gs://{bucket}/{object}`` format. + """ + class DeploymentStep(proto.Enum): + r"""The possible steps a deployment may be running. + + Values: + DEPLOYMENT_STEP_UNSPECIFIED (0): + Unspecified deployment step + PREPARING_STORAGE_BUCKET (1): + Infra Manager is creating a Google Cloud + Storage bucket to store artifacts and metadata + about the deployment and revision + DOWNLOADING_BLUEPRINT (2): + Downloading the blueprint onto the Google + Cloud Storage bucket + RUNNING_TF_INIT (3): + Initializing Terraform using ``terraform init`` + RUNNING_TF_PLAN (4): + Running ``terraform plan`` + RUNNING_TF_APPLY (5): + Actuating resources using Terraform using + ``terraform apply`` + RUNNING_TF_DESTROY (6): + Destroying resources using Terraform using + ``terraform destroy`` + RUNNING_TF_VALIDATE (7): + Validating the uploaded TF state file when + unlocking a deployment + UNLOCKING_DEPLOYMENT (8): + Unlocking a deployment + SUCCEEDED (9): + Operation was successful + FAILED (10): + Operation failed + VALIDATING_REPOSITORY (11): + Validating the provided repository. + RUNNING_QUOTA_VALIDATION (12): + Running quota validation + """ + DEPLOYMENT_STEP_UNSPECIFIED = 0 + PREPARING_STORAGE_BUCKET = 1 + DOWNLOADING_BLUEPRINT = 2 + RUNNING_TF_INIT = 3 + RUNNING_TF_PLAN = 4 + RUNNING_TF_APPLY = 5 + RUNNING_TF_DESTROY = 6 + RUNNING_TF_VALIDATE = 7 + UNLOCKING_DEPLOYMENT = 8 + SUCCEEDED = 9 + FAILED = 10 + VALIDATING_REPOSITORY = 11 + RUNNING_QUOTA_VALIDATION = 12 + + step: DeploymentStep = proto.Field( + proto.ENUM, + number=1, + enum=DeploymentStep, + ) + apply_results: 'ApplyResults' = proto.Field( + proto.MESSAGE, + number=2, + message='ApplyResults', + ) + build: str = proto.Field( + proto.STRING, + number=3, + ) + logs: str = proto.Field( + proto.STRING, + number=4, + ) + + +class Resource(proto.Message): + r"""Resource represents a Google Cloud Platform resource actuated + by IM. Resources are child resources of Revisions. + + Attributes: + name (str): + Output only. Resource name. Format: + ``projects/{project}/locations/{location}/deployments/{deployment}/revisions/{revision}/resources/{resource}`` + terraform_info (google.cloud.config_v1.types.ResourceTerraformInfo): + Output only. Terraform-specific info if this + resource was created using Terraform. + cai_assets (MutableMapping[str, google.cloud.config_v1.types.ResourceCAIInfo]): + Output only. Map of Cloud Asset Inventory + (CAI) type to CAI info (e.g. CAI ID). CAI type + format follows + https://cloud.google.com/asset-inventory/docs/supported-asset-types + intent (google.cloud.config_v1.types.Resource.Intent): + Output only. Intent of the resource. + state (google.cloud.config_v1.types.Resource.State): + Output only. Current state of the resource. + """ + class Intent(proto.Enum): + r"""Possible intent of the resource. + + Values: + INTENT_UNSPECIFIED (0): + The default value. This value is used if the + intent is omitted. + CREATE (1): + Infra Manager will create this Resource. + UPDATE (2): + Infra Manager will update this Resource. + DELETE (3): + Infra Manager will delete this Resource. + RECREATE (4): + Infra Manager will destroy and recreate this + Resource. + UNCHANGED (5): + Infra Manager will leave this Resource + untouched. + """ + INTENT_UNSPECIFIED = 0 + CREATE = 1 + UPDATE = 2 + DELETE = 3 + RECREATE = 4 + UNCHANGED = 5 + + class State(proto.Enum): + r"""Possible states of a resource. + + Values: + STATE_UNSPECIFIED (0): + The default value. This value is used if the + state is omitted. + PLANNED (1): + Resource has been planned for reconcile. + IN_PROGRESS (2): + Resource is actively reconciling into the + intended state. + RECONCILED (3): + Resource has reconciled to intended state. + FAILED (4): + Resource failed to reconcile. + """ + STATE_UNSPECIFIED = 0 + PLANNED = 1 + IN_PROGRESS = 2 + RECONCILED = 3 + FAILED = 4 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + terraform_info: 'ResourceTerraformInfo' = proto.Field( + proto.MESSAGE, + number=2, + message='ResourceTerraformInfo', + ) + cai_assets: MutableMapping[str, 'ResourceCAIInfo'] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=3, + message='ResourceCAIInfo', + ) + intent: Intent = proto.Field( + proto.ENUM, + number=4, + enum=Intent, + ) + state: State = proto.Field( + proto.ENUM, + number=5, + enum=State, + ) + + +class ResourceTerraformInfo(proto.Message): + r"""Terraform info of a Resource. + + Attributes: + address (str): + TF resource address that uniquely identifies + this resource within this deployment. + type_ (str): + TF resource type + id (str): + ID attribute of the TF resource + """ + + address: str = proto.Field( + proto.STRING, + number=1, + ) + type_: str = proto.Field( + proto.STRING, + number=2, + ) + id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ResourceCAIInfo(proto.Message): + r"""CAI info of a Resource. + + Attributes: + full_resource_name (str): + CAI resource name in the format following + https://cloud.google.com/apis/design/resource_names#full_resource_name + """ + + full_resource_name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetResourceRequest(proto.Message): + r"""A request to get a Resource from a 'GetResource' call. + + Attributes: + name (str): + Required. The name of the Resource in the format: + 'projects/{project_id}/locations/{location}/deployments/{deployment}/revisions/{revision}/resource/{resource}'. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListResourcesRequest(proto.Message): + r"""A request to list Resources passed to a 'ListResources' call. + + Attributes: + parent (str): + Required. The parent in whose context the Resources are + listed. The parent value is in the format: + 'projects/{project_id}/locations/{location}/deployments/{deployment}/revisions/{revision}'. + page_size (int): + When requesting a page of resources, 'page_size' specifies + number of resources to return. If unspecified, at most 500 + will be returned. The maximum value is 1000. + page_token (str): + Token returned by previous call to + 'ListResources' which specifies the position in + the list from where to continue listing the + resources. + filter (str): + Lists the Resources that match the filter expression. A + filter expression filters the resources listed in the + response. The expression must be of the form '{field} + {operator} {value}' where operators: '<', '>', '<=', '>=', + '!=', '=', ':' are supported (colon ':' represents a HAS + operator which is roughly synonymous with equality). {field} + can refer to a proto or JSON field, or a synthetic field. + Field names can be camelCase or snake_case. + + Examples: + + - Filter by name: name = + "projects/foo/locations/us-central1/deployments/dep/revisions/bar/resources/baz + order_by (str): + Field to use to sort the list. + """ + + 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 ListResourcesResponse(proto.Message): + r"""A response to a 'ListResources' call. Contains a list of + Resources. + + Attributes: + resources (MutableSequence[google.cloud.config_v1.types.Resource]): + List of [Resources][google.cloud.config.v1.Resource]. + next_page_token (str): + A token to request the next page of resources + from the 'ListResources' method. The value of an + empty string means that there are no more + resources to return. + unreachable (MutableSequence[str]): + Locations that could not be reached. + """ + + @property + def raw_page(self): + return self + + resources: MutableSequence['Resource'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Resource', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class Statefile(proto.Message): + r"""Contains info about a Terraform state file + + Attributes: + signed_uri (str): + Output only. Cloud Storage signed URI used + for downloading or uploading the state file. + """ + + signed_uri: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ExportDeploymentStatefileRequest(proto.Message): + r"""A request to export a state file passed to a + 'ExportDeploymentStatefile' call. + + Attributes: + parent (str): + Required. The parent in whose context the statefile is + listed. The parent value is in the format: + 'projects/{project_id}/locations/{location}/deployments/{deployment}'. + draft (bool): + Optional. If this flag is set to true, the + exported deployment state file will be the draft + state. This will enable the draft file to be + validated before copying it over to the working + state on unlock. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + draft: bool = proto.Field( + proto.BOOL, + number=3, + ) + + +class ExportRevisionStatefileRequest(proto.Message): + r"""A request to export a state file passed to a + 'ExportRevisionStatefile' call. + + Attributes: + parent (str): + Required. The parent in whose context the statefile is + listed. The parent value is in the format: + 'projects/{project_id}/locations/{location}/deployments/{deployment}/revisions/{revision}'. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ImportStatefileRequest(proto.Message): + r"""A request to import a state file passed to a + 'ImportStatefile' call. + + Attributes: + parent (str): + Required. The parent in whose context the statefile is + listed. The parent value is in the format: + 'projects/{project_id}/locations/{location}/deployments/{deployment}'. + lock_id (int): + Required. Lock ID of the lock file to verify + that the user who is importing the state file + previously locked the Deployment. + skip_draft (bool): + Optional. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + lock_id: int = proto.Field( + proto.INT64, + number=2, + ) + skip_draft: bool = proto.Field( + proto.BOOL, + number=3, + ) + + +class DeleteStatefileRequest(proto.Message): + r"""A request to delete a state file passed to a + 'DeleteStatefile' call. + + Attributes: + name (str): + Required. The name of the deployment in the format: + 'projects/{project_id}/locations/{location}/deployments/{deployment}'. + lock_id (int): + Required. Lock ID of the lock file to verify + that the user who is deleting the state file + previously locked the Deployment. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + lock_id: int = proto.Field( + proto.INT64, + number=2, + ) + + +class LockDeploymentRequest(proto.Message): + r"""A request to lock a deployment passed to a 'LockDeployment' + call. + + Attributes: + name (str): + Required. The name of the deployment in the format: + 'projects/{project_id}/locations/{location}/deployments/{deployment}'. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UnlockDeploymentRequest(proto.Message): + r"""A request to unlock a state file passed to a + 'UnlockDeployment' call. + + Attributes: + name (str): + Required. The name of the deployment in the format: + 'projects/{project_id}/locations/{location}/deployments/{deployment}'. + lock_id (int): + Required. Lock ID of the lock file to be + unlocked. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + lock_id: int = proto.Field( + proto.INT64, + number=2, + ) + + +class ExportLockInfoRequest(proto.Message): + r"""A request to get a state file lock info passed to a + 'ExportLockInfo' call. + + Attributes: + name (str): + Required. The name of the deployment in the format: + 'projects/{project_id}/locations/{location}/deployments/{deployment}'. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class LockInfo(proto.Message): + r"""Details about the lock which locked the deployment. + + Attributes: + lock_id (int): + Unique ID for the lock to be overridden with + generation ID in the backend. + operation (str): + Terraform operation, provided by the caller. + info (str): + Extra information to store with the lock, + provided by the caller. + who (str): + user@hostname when available + version (str): + Terraform version + create_time (google.protobuf.timestamp_pb2.Timestamp): + Time that the lock was taken. + """ + + lock_id: int = proto.Field( + proto.INT64, + number=1, + ) + operation: str = proto.Field( + proto.STRING, + number=2, + ) + info: str = proto.Field( + proto.STRING, + number=3, + ) + who: str = proto.Field( + proto.STRING, + number=4, + ) + version: str = proto.Field( + proto.STRING, + number=5, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + + +class Preview(proto.Message): + r"""A preview represents a set of actions Infra Manager would + perform to move the resources towards the desired state as + specified in the configuration. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + terraform_blueprint (google.cloud.config_v1.types.TerraformBlueprint): + The terraform blueprint to preview. + + This field is a member of `oneof`_ ``blueprint``. + name (str): + Identifier. Resource name of the preview. Resource name can + be user provided or server generated ID if unspecified. + Format: + ``projects/{project}/locations/{location}/previews/{preview}`` + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time the preview was created. + labels (MutableMapping[str, str]): + Optional. User-defined labels for the + preview. + state (google.cloud.config_v1.types.Preview.State): + Output only. Current state of the preview. + deployment (str): + Optional. Optional deployment reference. If + specified, the preview will be performed using + the provided deployment's current state and use + any relevant fields from the deployment unless + explicitly specified in the preview create + request. + preview_mode (google.cloud.config_v1.types.Preview.PreviewMode): + Optional. Current mode of preview. + service_account (str): + Required. User-specified Service Account (SA) credentials to + be used when previewing resources. Format: + ``projects/{projectID}/serviceAccounts/{serviceAccount}`` + artifacts_gcs_bucket (str): + Optional. User-defined location of Cloud Build logs, + artifacts, and in Google Cloud Storage. Format: + ``gs://{bucket}/{folder}`` A default bucket will be + bootstrapped if the field is not set or empty Default Bucket + Format: ``gs://--blueprint-config`` + Constraints: + + - The bucket needs to be in the same project as the + deployment + - The path cannot be within the path of ``gcs_source`` If + omitted and deployment resource ref provided has + artifacts_gcs_bucket defined, that artifact bucket is + used. + + This field is a member of `oneof`_ ``_artifacts_gcs_bucket``. + worker_pool (str): + Optional. The user-specified Worker Pool resource in which + the Cloud Build job will execute. Format + projects/{project}/locations/{location}/workerPools/{workerPoolId} + If this field is unspecified, the default Cloud Build worker + pool will be used. If omitted and deployment resource ref + provided has worker_pool defined, that worker pool is used. + + This field is a member of `oneof`_ ``_worker_pool``. + error_code (google.cloud.config_v1.types.Preview.ErrorCode): + Output only. Code describing any errors that + may have occurred. + error_status (google.rpc.status_pb2.Status): + Output only. Additional information regarding + the current state. + build (str): + Output only. Cloud Build instance UUID + associated with this preview. + tf_errors (MutableSequence[google.cloud.config_v1.types.TerraformError]): + Output only. Summary of errors encountered + during Terraform preview. It has a size limit of + 10, i.e. only top 10 errors will be summarized + here. + error_logs (str): + Output only. Link to tf-error.ndjson file, which contains + the full list of the errors encountered during a Terraform + preview. Format: ``gs://{bucket}/{object}``. + preview_artifacts (google.cloud.config_v1.types.PreviewArtifacts): + Output only. Artifacts from preview. + logs (str): + Output only. Location of preview logs in + ``gs://{bucket}/{object}`` format. + tf_version (str): + Output only. The current Terraform version + set on the preview. It is in the format of + "Major.Minor.Patch", for example, "1.3.10". + tf_version_constraint (str): + Optional. The user-specified Terraform + version constraint. Example: "=1.3.10". + + This field is a member of `oneof`_ ``_tf_version_constraint``. + annotations (MutableMapping[str, str]): + Optional. Arbitrary key-value metadata + storage e.g. to help client tools identify + preview during automation. See + https://google.aip.dev/148#annotations for + details on format and size limitations. + provider_config (google.cloud.config_v1.types.ProviderConfig): + Optional. This field specifies the provider + configurations. + """ + class State(proto.Enum): + r"""Possible states of a preview. + + Values: + STATE_UNSPECIFIED (0): + The default value. This value is used if the + state is unknown. + CREATING (1): + The preview is being created. + SUCCEEDED (2): + The preview has succeeded. + APPLYING (3): + The preview is being applied. + STALE (4): + The preview is stale. A preview can become + stale if a revision has been applied after this + preview was created. + DELETING (5): + The preview is being deleted. + FAILED (6): + The preview has encountered an unexpected + error. + DELETED (7): + The preview has been deleted. + """ + STATE_UNSPECIFIED = 0 + CREATING = 1 + SUCCEEDED = 2 + APPLYING = 3 + STALE = 4 + DELETING = 5 + FAILED = 6 + DELETED = 7 + + class PreviewMode(proto.Enum): + r"""Preview mode provides options for customizing preview + operations. + + Values: + PREVIEW_MODE_UNSPECIFIED (0): + Unspecified policy, default mode will be + used. + DEFAULT (1): + DEFAULT mode generates an execution plan for + reconciling current resource state into expected + resource state. + DELETE (2): + DELETE mode generates as execution plan for + destroying current resources. + """ + PREVIEW_MODE_UNSPECIFIED = 0 + DEFAULT = 1 + DELETE = 2 + + class ErrorCode(proto.Enum): + r"""Possible errors that can occur with previews. + + Values: + ERROR_CODE_UNSPECIFIED (0): + No error code was specified. + CLOUD_BUILD_PERMISSION_DENIED (1): + Cloud Build failed due to a permissions + issue. + BUCKET_CREATION_PERMISSION_DENIED (2): + Cloud Storage bucket failed to create due to + a permissions issue. + BUCKET_CREATION_FAILED (3): + Cloud Storage bucket failed for a + non-permissions-related issue. + DEPLOYMENT_LOCK_ACQUIRE_FAILED (4): + Acquiring lock on provided deployment + reference failed. + PREVIEW_BUILD_API_FAILED (5): + Preview encountered an error when trying to + access Cloud Build API. + PREVIEW_BUILD_RUN_FAILED (6): + Preview created a build but build failed and + logs were generated. + """ + ERROR_CODE_UNSPECIFIED = 0 + CLOUD_BUILD_PERMISSION_DENIED = 1 + BUCKET_CREATION_PERMISSION_DENIED = 2 + BUCKET_CREATION_FAILED = 3 + DEPLOYMENT_LOCK_ACQUIRE_FAILED = 4 + PREVIEW_BUILD_API_FAILED = 5 + PREVIEW_BUILD_RUN_FAILED = 6 + + terraform_blueprint: 'TerraformBlueprint' = proto.Field( + proto.MESSAGE, + number=6, + oneof='blueprint', + message='TerraformBlueprint', + ) + name: str = proto.Field( + proto.STRING, + number=1, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=3, + ) + state: State = proto.Field( + proto.ENUM, + number=4, + enum=State, + ) + deployment: str = proto.Field( + proto.STRING, + number=5, + ) + preview_mode: PreviewMode = proto.Field( + proto.ENUM, + number=15, + enum=PreviewMode, + ) + service_account: str = proto.Field( + proto.STRING, + number=7, + ) + artifacts_gcs_bucket: str = proto.Field( + proto.STRING, + number=8, + optional=True, + ) + worker_pool: str = proto.Field( + proto.STRING, + number=9, + optional=True, + ) + error_code: ErrorCode = proto.Field( + proto.ENUM, + number=10, + enum=ErrorCode, + ) + error_status: status_pb2.Status = proto.Field( + proto.MESSAGE, + number=11, + message=status_pb2.Status, + ) + build: str = proto.Field( + proto.STRING, + number=12, + ) + tf_errors: MutableSequence['TerraformError'] = proto.RepeatedField( + proto.MESSAGE, + number=13, + message='TerraformError', + ) + error_logs: str = proto.Field( + proto.STRING, + number=14, + ) + preview_artifacts: 'PreviewArtifacts' = proto.Field( + proto.MESSAGE, + number=16, + message='PreviewArtifacts', + ) + logs: str = proto.Field( + proto.STRING, + number=17, + ) + tf_version: str = proto.Field( + proto.STRING, + number=18, + ) + tf_version_constraint: str = proto.Field( + proto.STRING, + number=19, + optional=True, + ) + annotations: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=20, + ) + provider_config: 'ProviderConfig' = proto.Field( + proto.MESSAGE, + number=21, + message='ProviderConfig', + ) + + +class PreviewOperationMetadata(proto.Message): + r"""Ephemeral metadata content describing the state of a preview + operation. + + Attributes: + step (google.cloud.config_v1.types.PreviewOperationMetadata.PreviewStep): + The current step the preview operation is + running. + preview_artifacts (google.cloud.config_v1.types.PreviewArtifacts): + Artifacts from preview. + logs (str): + Output only. Location of preview logs in + ``gs://{bucket}/{object}`` format. + build (str): + Output only. Cloud Build instance UUID + associated with this preview. + """ + class PreviewStep(proto.Enum): + r"""The possible steps a preview may be running. + + Values: + PREVIEW_STEP_UNSPECIFIED (0): + Unspecified preview step. + PREPARING_STORAGE_BUCKET (1): + Infra Manager is creating a Google Cloud + Storage bucket to store artifacts and metadata + about the preview. + DOWNLOADING_BLUEPRINT (2): + Downloading the blueprint onto the Google + Cloud Storage bucket. + RUNNING_TF_INIT (3): + Initializing Terraform using ``terraform init``. + RUNNING_TF_PLAN (4): + Running ``terraform plan``. + FETCHING_DEPLOYMENT (5): + Fetching a deployment. + LOCKING_DEPLOYMENT (6): + Locking a deployment. + UNLOCKING_DEPLOYMENT (7): + Unlocking a deployment. + SUCCEEDED (8): + Operation was successful. + FAILED (9): + Operation failed. + VALIDATING_REPOSITORY (10): + Validating the provided repository. + """ + PREVIEW_STEP_UNSPECIFIED = 0 + PREPARING_STORAGE_BUCKET = 1 + DOWNLOADING_BLUEPRINT = 2 + RUNNING_TF_INIT = 3 + RUNNING_TF_PLAN = 4 + FETCHING_DEPLOYMENT = 5 + LOCKING_DEPLOYMENT = 6 + UNLOCKING_DEPLOYMENT = 7 + SUCCEEDED = 8 + FAILED = 9 + VALIDATING_REPOSITORY = 10 + + step: PreviewStep = proto.Field( + proto.ENUM, + number=1, + enum=PreviewStep, + ) + preview_artifacts: 'PreviewArtifacts' = proto.Field( + proto.MESSAGE, + number=2, + message='PreviewArtifacts', + ) + logs: str = proto.Field( + proto.STRING, + number=3, + ) + build: str = proto.Field( + proto.STRING, + number=4, + ) + + +class PreviewArtifacts(proto.Message): + r"""Artifacts created by preview. + + Attributes: + content (str): + Output only. Location of a blueprint copy and other content + in Google Cloud Storage. Format: ``gs://{bucket}/{object}`` + artifacts (str): + Output only. Location of artifacts in Google Cloud Storage. + Format: ``gs://{bucket}/{object}`` + """ + + content: str = proto.Field( + proto.STRING, + number=1, + ) + artifacts: str = proto.Field( + proto.STRING, + number=2, + ) + + +class CreatePreviewRequest(proto.Message): + r"""A request to create a preview. + + Attributes: + parent (str): + Required. The parent in whose context the Preview is + created. The parent value is in the format: + 'projects/{project_id}/locations/{location}'. + preview_id (str): + Optional. The preview ID. + preview (google.cloud.config_v1.types.Preview): + Required. [Preview][google.cloud.config.v1.Preview] 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 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, + ) + preview_id: str = proto.Field( + proto.STRING, + number=2, + ) + preview: 'Preview' = proto.Field( + proto.MESSAGE, + number=3, + message='Preview', + ) + request_id: str = proto.Field( + proto.STRING, + number=4, + ) + + +class GetPreviewRequest(proto.Message): + r"""A request to get details about a preview. + + Attributes: + name (str): + Required. The name of the preview. Format: + 'projects/{project_id}/locations/{location}/previews/{preview}'. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListPreviewsRequest(proto.Message): + r"""A request to list all previews for a given project and + location. + + Attributes: + parent (str): + Required. The parent in whose context the Previews are + listed. The parent value is in the format: + 'projects/{project_id}/locations/{location}'. + page_size (int): + Optional. When requesting a page of resources, 'page_size' + specifies number of resources to return. If unspecified, at + most 500 will be returned. The maximum value is 1000. + page_token (str): + Optional. Token returned by previous call to + 'ListDeployments' which specifies the position + in the list from where to continue listing the + resources. + filter (str): + Optional. Lists the Deployments that match the filter + expression. A filter expression filters the resources listed + in the response. The expression must be of the form '{field} + {operator} {value}' where operators: '<', '>', '<=', '>=', + '!=', '=', ':' are supported (colon ':' represents a HAS + operator which is roughly synonymous with equality). {field} + can refer to a proto or JSON field, or a synthetic field. + Field names can be camelCase or snake_case. + + Examples: + + - Filter by name: name = + "projects/foo/locations/us-central1/deployments/bar + + - Filter by labels: + + - Resources that have a key called 'foo' labels.foo:\* + - Resources that have a key called 'foo' whose value is + 'bar' labels.foo = bar + + - Filter by state: + + - Deployments in CREATING state. state=CREATING + order_by (str): + Optional. Field to use to sort the list. + """ + + 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 ListPreviewsResponse(proto.Message): + r"""A response to a ``ListPreviews`` call. Contains a list of Previews. + + Attributes: + previews (MutableSequence[google.cloud.config_v1.types.Preview]): + List of [Previews][google.cloud.config.v1.Preview]. + next_page_token (str): + Token to be supplied to the next ListPreviews request via + ``page_token`` to obtain the next set of results. + unreachable (MutableSequence[str]): + Locations that could not be reached. + """ + + @property + def raw_page(self): + return self + + previews: MutableSequence['Preview'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Preview', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class DeletePreviewRequest(proto.Message): + r"""A request to delete a preview. + + Attributes: + name (str): + Required. The name of the Preview in the format: + 'projects/{project_id}/locations/{location}/previews/{preview}'. + 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 ExportPreviewResultRequest(proto.Message): + r"""A request to export preview results. + + Attributes: + parent (str): + Required. The preview whose results should be exported. The + preview value is in the format: + 'projects/{project_id}/locations/{location}/previews/{preview}'. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ExportPreviewResultResponse(proto.Message): + r"""A response to ``ExportPreviewResult`` call. Contains preview + results. + + Attributes: + result (google.cloud.config_v1.types.PreviewResult): + Output only. Signed URLs for accessing the + plan files. + """ + + result: 'PreviewResult' = proto.Field( + proto.MESSAGE, + number=1, + message='PreviewResult', + ) + + +class PreviewResult(proto.Message): + r"""Contains a signed Cloud Storage URLs. + + Attributes: + binary_signed_uri (str): + Output only. Plan binary signed URL + json_signed_uri (str): + Output only. Plan JSON signed URL + """ + + binary_signed_uri: str = proto.Field( + proto.STRING, + number=1, + ) + json_signed_uri: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetTerraformVersionRequest(proto.Message): + r"""The request message for the GetTerraformVersion method. + + Attributes: + name (str): + Required. The name of the TerraformVersion. Format: + 'projects/{project_id}/locations/{location}/terraformVersions/{terraform_version}' + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListTerraformVersionsRequest(proto.Message): + r"""The request message for the ListTerraformVersions method. + + Attributes: + parent (str): + Required. The parent in whose context the TerraformVersions + are listed. The parent value is in the format: + 'projects/{project_id}/locations/{location}'. + page_size (int): + Optional. When requesting a page of terraform versions, + 'page_size' specifies number of terraform versions to + return. If unspecified, at most 500 will be returned. The + maximum value is 1000. + page_token (str): + Optional. Token returned by previous call to + 'ListTerraformVersions' which specifies the + position in the list from where to continue + listing the terraform versions. + filter (str): + Optional. Lists the TerraformVersions that match the filter + expression. A filter expression filters the resources listed + in the response. The expression must be of the form '{field} + {operator} {value}' where operators: '<', '>', '<=', '>=', + '!=', '=', ':' are supported (colon ':' represents a HAS + operator which is roughly synonymous with equality). {field} + can refer to a proto or JSON field, or a synthetic field. + Field names can be camelCase or snake_case. + order_by (str): + Optional. Field to use to sort the list. + """ + + 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 ListTerraformVersionsResponse(proto.Message): + r"""The response message for the ``ListTerraformVersions`` method. + + Attributes: + terraform_versions (MutableSequence[google.cloud.config_v1.types.TerraformVersion]): + List of + [TerraformVersion][google.cloud.config.v1.TerraformVersion]s. + next_page_token (str): + Token to be supplied to the next ListTerraformVersions + request via ``page_token`` to obtain the next set of + results. + unreachable (MutableSequence[str]): + Unreachable resources, if any. + """ + + @property + def raw_page(self): + return self + + terraform_versions: MutableSequence['TerraformVersion'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='TerraformVersion', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class TerraformVersion(proto.Message): + r"""A TerraformVersion represents the support state the + corresponding Terraform version. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + Identifier. The version name is in the format: + 'projects/{project_id}/locations/{location}/terraformVersions/{terraform_version}'. + state (google.cloud.config_v1.types.TerraformVersion.State): + Output only. The state of the version, + ACTIVE, DEPRECATED or OBSOLETE. + support_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. When the version is supported. + deprecate_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. When the version is deprecated. + + This field is a member of `oneof`_ ``_deprecate_time``. + obsolete_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. When the version is obsolete. + + This field is a member of `oneof`_ ``_obsolete_time``. + """ + class State(proto.Enum): + r"""Possible states of a TerraformVersion. + + Values: + STATE_UNSPECIFIED (0): + The default value. This value is used if the + state is omitted. + ACTIVE (1): + The version is actively supported. + DEPRECATED (2): + The version is deprecated. + OBSOLETE (3): + The version is obsolete. + """ + STATE_UNSPECIFIED = 0 + ACTIVE = 1 + DEPRECATED = 2 + OBSOLETE = 3 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + state: State = proto.Field( + proto.ENUM, + number=2, + enum=State, + ) + support_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + deprecate_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + optional=True, + message=timestamp_pb2.Timestamp, + ) + obsolete_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + optional=True, + message=timestamp_pb2.Timestamp, + ) + + +class ResourceChangeTerraformInfo(proto.Message): + r"""Terraform info of a ResourceChange. + + Attributes: + address (str): + Output only. TF resource address that + uniquely identifies the resource. + type_ (str): + Output only. TF resource type. + resource_name (str): + Output only. TF resource name. + provider (str): + Output only. TF resource provider. + actions (MutableSequence[str]): + Output only. TF resource actions. + """ + + address: str = proto.Field( + proto.STRING, + number=1, + ) + type_: str = proto.Field( + proto.STRING, + number=2, + ) + resource_name: str = proto.Field( + proto.STRING, + number=3, + ) + provider: str = proto.Field( + proto.STRING, + number=4, + ) + actions: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=5, + ) + + +class ResourceChange(proto.Message): + r"""A resource change represents a change to a resource in the + state file. + + Attributes: + name (str): + Identifier. The name of the resource change. Format: + 'projects/{project_id}/locations/{location}/previews/{preview}/resourceChanges/{resource_change}'. + terraform_info (google.cloud.config_v1.types.ResourceChangeTerraformInfo): + Output only. Terraform info of the resource + change. + intent (google.cloud.config_v1.types.ResourceChange.Intent): + Output only. The intent of the resource + change. + property_changes (MutableSequence[google.cloud.config_v1.types.PropertyChange]): + Output only. The property changes of the + resource change. + """ + class Intent(proto.Enum): + r"""Possible intent of the resource change. + + Values: + INTENT_UNSPECIFIED (0): + The default value. + CREATE (1): + The resource will be created. + UPDATE (2): + The resource will be updated. + DELETE (3): + The resource will be deleted. + RECREATE (4): + The resource will be recreated. + UNCHANGED (5): + The resource will be untouched. + """ + INTENT_UNSPECIFIED = 0 + CREATE = 1 + UPDATE = 2 + DELETE = 3 + RECREATE = 4 + UNCHANGED = 5 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + terraform_info: 'ResourceChangeTerraformInfo' = proto.Field( + proto.MESSAGE, + number=2, + message='ResourceChangeTerraformInfo', + ) + intent: Intent = proto.Field( + proto.ENUM, + number=3, + enum=Intent, + ) + property_changes: MutableSequence['PropertyChange'] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='PropertyChange', + ) + + +class PropertyChange(proto.Message): + r"""A property change represents a change to a property in the + state file. + + Attributes: + path (str): + Output only. The path of the property change. + before_sensitive_paths (MutableSequence[str]): + Output only. The paths of sensitive fields in ``before``. + Paths are relative to ``path``. + before (google.protobuf.struct_pb2.Value): + Output only. Representations of the object + value before the actions. + after_sensitive_paths (MutableSequence[str]): + Output only. The paths of sensitive fields in ``after``. + Paths are relative to ``path``. + after (google.protobuf.struct_pb2.Value): + Output only. Representations of the object + value after the actions. + """ + + path: str = proto.Field( + proto.STRING, + number=1, + ) + before_sensitive_paths: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + before: struct_pb2.Value = proto.Field( + proto.MESSAGE, + number=3, + message=struct_pb2.Value, + ) + after_sensitive_paths: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=4, + ) + after: struct_pb2.Value = proto.Field( + proto.MESSAGE, + number=5, + message=struct_pb2.Value, + ) + + +class ListResourceChangesRequest(proto.Message): + r"""The request message for the ListResourceChanges method. + + Attributes: + parent (str): + Required. The parent in whose context the ResourceChanges + are listed. The parent value is in the format: + 'projects/{project_id}/locations/{location}/previews/{preview}'. + page_size (int): + Optional. When requesting a page of resource changes, + 'page_size' specifies number of resource changes to return. + If unspecified, at most 500 will be returned. The maximum + value is 1000. + page_token (str): + Optional. Token returned by previous call to + 'ListResourceChanges' which specifies the + position in the list from where to continue + listing the resource changes. + filter (str): + Optional. Lists the resource changes that match the filter + expression. A filter expression filters the resource changes + listed in the response. The expression must be of the form + '{field} {operator} {value}' where operators: '<', '>', + '<=', '>=', '!=', '=', ':' are supported (colon ':' + represents a HAS operator which is roughly synonymous with + equality). {field} can refer to a proto or JSON field, or a + synthetic field. Field names can be camelCase or snake_case. + + Examples: + + - Filter by name: name = + "projects/foo/locations/us-central1/previews/dep/resourceChanges/baz + order_by (str): + Optional. Field to use to sort the list. + """ + + 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 ListResourceChangesResponse(proto.Message): + r"""A response to a 'ListResourceChanges' call. Contains a list + of ResourceChanges. + + Attributes: + resource_changes (MutableSequence[google.cloud.config_v1.types.ResourceChange]): + List of ResourceChanges. + next_page_token (str): + A token to request the next page of resources + from the 'ListResourceChanges' method. The value + of an empty string means that there are no more + resources to return. + unreachable (MutableSequence[str]): + Unreachable resources, if any. + """ + + @property + def raw_page(self): + return self + + resource_changes: MutableSequence['ResourceChange'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='ResourceChange', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class GetResourceChangeRequest(proto.Message): + r"""The request message for the GetResourceChange method. + + Attributes: + name (str): + Required. The name of the resource change to retrieve. + Format: + 'projects/{project_id}/locations/{location}/previews/{preview}/resourceChanges/{resource_change}'. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ResourceDriftTerraformInfo(proto.Message): + r"""Terraform info of a ResourceChange. + + Attributes: + address (str): + Output only. The address of the drifted + resource. + type_ (str): + Output only. The type of the drifted + resource. + resource_name (str): + Output only. TF resource name. + provider (str): + Output only. The provider of the drifted + resource. + """ + + address: str = proto.Field( + proto.STRING, + number=1, + ) + type_: str = proto.Field( + proto.STRING, + number=2, + ) + resource_name: str = proto.Field( + proto.STRING, + number=3, + ) + provider: str = proto.Field( + proto.STRING, + number=4, + ) + + +class ResourceDrift(proto.Message): + r"""A resource drift represents a drift to a resource in the + state file. + + Attributes: + name (str): + Identifier. The name of the resource drift. Format: + 'projects/{project_id}/locations/{location}/previews/{preview}/resourceDrifts/{resource_drift}'. + terraform_info (google.cloud.config_v1.types.ResourceDriftTerraformInfo): + Output only. Terraform info of the resource + drift. + property_drifts (MutableSequence[google.cloud.config_v1.types.PropertyDrift]): + Output only. The property drifts of the + resource drift. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + terraform_info: 'ResourceDriftTerraformInfo' = proto.Field( + proto.MESSAGE, + number=2, + message='ResourceDriftTerraformInfo', + ) + property_drifts: MutableSequence['PropertyDrift'] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='PropertyDrift', + ) + + +class PropertyDrift(proto.Message): + r"""A property drift represents a drift to a property in the + state file. + + Attributes: + path (str): + Output only. The path of the property drift. + before_sensitive_paths (MutableSequence[str]): + Output only. The paths of sensitive fields in ``before``. + Paths are relative to ``path``. + before (google.protobuf.struct_pb2.Value): + Output only. Representations of the object + value before the actions. + after_sensitive_paths (MutableSequence[str]): + Output only. The paths of sensitive fields in ``after``. + Paths are relative to ``path``. + after (google.protobuf.struct_pb2.Value): + Output only. Representations of the object + value after the actions. + """ + + path: str = proto.Field( + proto.STRING, + number=1, + ) + before_sensitive_paths: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + before: struct_pb2.Value = proto.Field( + proto.MESSAGE, + number=3, + message=struct_pb2.Value, + ) + after_sensitive_paths: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=4, + ) + after: struct_pb2.Value = proto.Field( + proto.MESSAGE, + number=5, + message=struct_pb2.Value, + ) + + +class ListResourceDriftsRequest(proto.Message): + r"""The request message for the ListResourceDrifts method. + + Attributes: + parent (str): + Required. The parent in whose context the ResourceDrifts are + listed. The parent value is in the format: + 'projects/{project_id}/locations/{location}/previews/{preview}'. + page_size (int): + Optional. When requesting a page of resource drifts, + 'page_size' specifies number of resource drifts to return. + If unspecified, at most 500 will be returned. The maximum + value is 1000. + page_token (str): + Optional. Token returned by previous call to + 'ListResourceDrifts' which specifies the + position in the list from where to continue + listing the resource drifts. + filter (str): + Optional. Lists the resource drifts that match the filter + expression. A filter expression filters the resource drifts + listed in the response. The expression must be of the form + '{field} {operator} {value}' where operators: '<', '>', + '<=', '>=', '!=', '=', ':' are supported (colon ':' + represents a HAS operator which is roughly synonymous with + equality). {field} can refer to a proto or JSON field, or a + synthetic field. Field names can be camelCase or snake_case. + + Examples: + + - Filter by name: name = + "projects/foo/locations/us-central1/previews/dep/resourceDrifts/baz + order_by (str): + Optional. Field to use to sort the list. + """ + + 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 ListResourceDriftsResponse(proto.Message): + r"""A response to a 'ListResourceDrifts' call. Contains a list of + ResourceDrifts. + + Attributes: + resource_drifts (MutableSequence[google.cloud.config_v1.types.ResourceDrift]): + List of ResourceDrifts. + next_page_token (str): + A token to request the next page of resources + from the 'ListResourceDrifts' method. The value + of an empty string means that there are no more + resources to return. + unreachable (MutableSequence[str]): + Unreachable resources, if any. + """ + + @property + def raw_page(self): + return self + + resource_drifts: MutableSequence['ResourceDrift'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='ResourceDrift', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class GetResourceDriftRequest(proto.Message): + r"""The request message for the GetResourceDrift method. + + Attributes: + name (str): + Required. The name of the resource drift to retrieve. + Format: + 'projects/{project_id}/locations/{location}/previews/{preview}/resourceDrifts/{resource_drift}'. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ProviderConfig(proto.Message): + r"""ProviderConfig contains the provider configurations. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + source_type (google.cloud.config_v1.types.ProviderConfig.ProviderSource): + Optional. ProviderSource specifies the source + type of the provider. + + This field is a member of `oneof`_ ``_source_type``. + """ + class ProviderSource(proto.Enum): + r"""ProviderSource represents the source type of the provider. + + Values: + PROVIDER_SOURCE_UNSPECIFIED (0): + Unspecified source type, default to public + sources. + SERVICE_MAINTAINED (1): + Service maintained provider source type. + """ + PROVIDER_SOURCE_UNSPECIFIED = 0 + SERVICE_MAINTAINED = 1 + + source_type: ProviderSource = proto.Field( + proto.ENUM, + number=1, + optional=True, + enum=ProviderSource, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-config/v1/mypy.ini b/owl-bot-staging/google-cloud-config/v1/mypy.ini new file mode 100644 index 000000000000..574c5aed394b --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/owl-bot-staging/google-cloud-config/v1/noxfile.py b/owl-bot-staging/google-cloud-config/v1/noxfile.py new file mode 100644 index 000000000000..bd3a52533ecd --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/noxfile.py @@ -0,0 +1,591 @@ +# -*- 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. +# +import os +import pathlib +import re +import shutil + +from typing import Dict, List +import warnings + +import nox + +BLACK_VERSION = "black[jupyter]==23.7.0" +ISORT_VERSION = "isort==5.11.0" + +LINT_PATHS = ["docs", "google", "tests", "noxfile.py", "setup.py"] + +ALL_PYTHON = [ + "3.7", + "3.8", + "3.9", + "3.10", + "3.11", + "3.12", + "3.13", +] + +DEFAULT_PYTHON_VERSION = ALL_PYTHON[-1] + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" +PACKAGE_NAME = "google-cloud-config" + +UNIT_TEST_STANDARD_DEPENDENCIES = [ + "mock", + "asyncmock", + "pytest", + "pytest-cov", + "pytest-asyncio", +] +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_BY_PYTHON: Dict[str, List[str]] = {} + +SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ["3.8", "3.9", "3.10", "3.11", "3.12", "3.13"] +SYSTEM_TEST_STANDARD_DEPENDENCIES = [ + "mock", + "pytest", + "google-cloud-testutils", +] +SYSTEM_TEST_EXTERNAL_DEPENDENCIES: List[str] = [] +SYSTEM_TEST_LOCAL_DEPENDENCIES: List[str] = [] +SYSTEM_TEST_DEPENDENCIES: List[str] = [] +SYSTEM_TEST_EXTRAS: List[str] = [] +SYSTEM_TEST_EXTRAS_BY_PYTHON: Dict[str, List[str]] = {} + +nox.options.sessions = [ + "unit", + "system", + "cover", + "lint", + "lint_setup_py", + "blacken", + "docs", +] + +# Error if a python version is missing +nox.options.error_on_missing_interpreters = True + + +@nox.session(python=ALL_PYTHON) +def mypy(session): + """Run the type checker.""" + session.install( + # TODO(https://github.com/googleapis/gapic-generator-python/issues/2410): Use the latest version of mypy + "mypy<1.16.0", + "types-requests", + "types-protobuf", + ) + session.install(".") + session.run( + "mypy", + "-p", + "google", + ) + + +@nox.session +def update_lower_bounds(session): + """Update lower bounds in constraints.txt to match setup.py""" + session.install("google-cloud-testutils") + session.install(".") + + session.run( + "lower-bound-checker", + "update", + "--package-name", + PACKAGE_NAME, + "--constraints-file", + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + + +@nox.session +def check_lower_bounds(session): + """Check lower bounds in setup.py are reflected in constraints file""" + session.install("google-cloud-testutils") + session.install(".") + + session.run( + "lower-bound-checker", + "check", + "--package-name", + PACKAGE_NAME, + "--constraints-file", + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint(session): + """Run linters. + + Returns a failure if the linters find linting errors or sufficiently + serious code quality issues. + """ + session.install("flake8", BLACK_VERSION) + session.run( + "black", + "--check", + *LINT_PATHS, + ) + + session.run("flake8", "google", "tests") + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def blacken(session): + """Run black. Format code to uniform standard.""" + session.install(BLACK_VERSION) + session.run( + "black", + *LINT_PATHS, + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def format(session): + """ + Run isort to sort imports. Then run black + to format code to uniform standard. + """ + session.install(BLACK_VERSION, ISORT_VERSION) + # Use the --fss option to sort imports using strict alphabetical order. + # See https://pycqa.github.io/isort/docs/configuration/options.html#force-sort-within-sections + session.run( + "isort", + "--fss", + *LINT_PATHS, + ) + session.run( + "black", + *LINT_PATHS, + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint_setup_py(session): + """Verify that setup.py is valid (including RST check).""" + session.install("setuptools", "docutils", "pygments") + session.run("python", "setup.py", "check", "--restructuredtext", "--strict") + + +def install_unittest_dependencies(session, *constraints): + standard_deps = UNIT_TEST_STANDARD_DEPENDENCIES + UNIT_TEST_DEPENDENCIES + session.install(*standard_deps, *constraints) + + if UNIT_TEST_EXTERNAL_DEPENDENCIES: + warnings.warn( + "'unit_test_external_dependencies' is deprecated. Instead, please " + "use 'unit_test_dependencies' or 'unit_test_local_dependencies'.", + DeprecationWarning, + ) + session.install(*UNIT_TEST_EXTERNAL_DEPENDENCIES, *constraints) + + if UNIT_TEST_LOCAL_DEPENDENCIES: + session.install(*UNIT_TEST_LOCAL_DEPENDENCIES, *constraints) + + if UNIT_TEST_EXTRAS_BY_PYTHON: + extras = UNIT_TEST_EXTRAS_BY_PYTHON.get(session.python, []) + elif UNIT_TEST_EXTRAS: + extras = UNIT_TEST_EXTRAS + else: + extras = [] + + if extras: + session.install("-e", f".[{','.join(extras)}]", *constraints) + else: + session.install("-e", ".", *constraints) + + +@nox.session(python=ALL_PYTHON) +@nox.parametrize( + "protobuf_implementation", + ["python", "upb", "cpp"], +) +def unit(session, protobuf_implementation): + # Install all test dependencies, then install this package in-place. + + if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"): + session.skip("cpp implementation is not supported in python 3.11+") + + constraints_path = str( + CURRENT_DIRECTORY / "testing" / f"constraints-{session.python}.txt" + ) + install_unittest_dependencies(session, "-c", constraints_path) + + # TODO(https://github.com/googleapis/synthtool/issues/1976): + # Remove the 'cpp' implementation once support for Protobuf 3.x is dropped. + # The 'cpp' implementation requires Protobuf<4. + if protobuf_implementation == "cpp": + session.install("protobuf<4") + + # Run py.test against the unit tests. + session.run( + "py.test", + "--quiet", + f"--junitxml=unit_{session.python}_sponge_log.xml", + "--cov=google", + "--cov=tests/unit", + "--cov-append", + "--cov-config=.coveragerc", + "--cov-report=", + "--cov-fail-under=0", + os.path.join("tests", "unit"), + *session.posargs, + env={ + "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, + }, + ) + + +def install_systemtest_dependencies(session, *constraints): + session.install("--pre", "grpcio") + + session.install(*SYSTEM_TEST_STANDARD_DEPENDENCIES, *constraints) + + if SYSTEM_TEST_EXTERNAL_DEPENDENCIES: + session.install(*SYSTEM_TEST_EXTERNAL_DEPENDENCIES, *constraints) + + if SYSTEM_TEST_LOCAL_DEPENDENCIES: + session.install("-e", *SYSTEM_TEST_LOCAL_DEPENDENCIES, *constraints) + + if SYSTEM_TEST_DEPENDENCIES: + session.install("-e", *SYSTEM_TEST_DEPENDENCIES, *constraints) + + if SYSTEM_TEST_EXTRAS_BY_PYTHON: + extras = SYSTEM_TEST_EXTRAS_BY_PYTHON.get(session.python, []) + elif SYSTEM_TEST_EXTRAS: + extras = SYSTEM_TEST_EXTRAS + else: + extras = [] + + if extras: + session.install("-e", f".[{','.join(extras)}]", *constraints) + else: + session.install("-e", ".", *constraints) + + +@nox.session(python=SYSTEM_TEST_PYTHON_VERSIONS) +def system(session): + """Run the system test suite.""" + constraints_path = str( + CURRENT_DIRECTORY / "testing" / f"constraints-{session.python}.txt" + ) + system_test_path = os.path.join("tests", "system.py") + system_test_folder_path = os.path.join("tests", "system") + + # Check the value of `RUN_SYSTEM_TESTS` env var. It defaults to true. + if os.environ.get("RUN_SYSTEM_TESTS", "true") == "false": + session.skip("RUN_SYSTEM_TESTS is set to false, skipping") + # Install pyopenssl for mTLS testing. + if os.environ.get("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") == "true": + session.install("pyopenssl") + + system_test_exists = os.path.exists(system_test_path) + system_test_folder_exists = os.path.exists(system_test_folder_path) + # Sanity check: only run tests if found. + if not system_test_exists and not system_test_folder_exists: + session.skip("System tests were not found") + + install_systemtest_dependencies(session, "-c", constraints_path) + + # Run py.test against the system tests. + if system_test_exists: + session.run( + "py.test", + "--quiet", + f"--junitxml=system_{session.python}_sponge_log.xml", + system_test_path, + *session.posargs, + ) + if system_test_folder_exists: + session.run( + "py.test", + "--quiet", + f"--junitxml=system_{session.python}_sponge_log.xml", + system_test_folder_path, + *session.posargs, + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def cover(session): + """Run the final coverage report. + + This outputs the coverage report aggregating coverage from the unit + test runs (not system test runs), and then erases coverage data. + """ + session.install("coverage", "pytest-cov") + session.run("coverage", "report", "--show-missing", "--fail-under=100") + + session.run("coverage", "erase") + + +@nox.session(python="3.10") +def docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install( + # We need to pin to specific versions of the `sphinxcontrib-*` packages + # which still support sphinx 4.x. + # See https://github.com/googleapis/sphinx-docfx-yaml/issues/344 + # and https://github.com/googleapis/sphinx-docfx-yaml/issues/345. + "sphinxcontrib-applehelp==1.0.4", + "sphinxcontrib-devhelp==1.0.2", + "sphinxcontrib-htmlhelp==2.0.1", + "sphinxcontrib-qthelp==1.0.3", + "sphinxcontrib-serializinghtml==1.1.5", + "sphinx==4.5.0", + "alabaster", + "recommonmark", + ) + + shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) + session.run( + "sphinx-build", + "-W", # warnings as errors + "-T", # show full traceback on exception + "-N", # no colors + "-b", "html", # builder + "-d", os.path.join("docs", "_build", "doctrees", ""), # cache directory + # paths to build: + os.path.join("docs", ""), + os.path.join("docs", "_build", "html", ""), + ) + + +@nox.session(python="3.10") +def docfx(session): + """Build the docfx yaml files for this library.""" + + session.install("-e", ".") + session.install( + # We need to pin to specific versions of the `sphinxcontrib-*` packages + # which still support sphinx 4.x. + # See https://github.com/googleapis/sphinx-docfx-yaml/issues/344 + # and https://github.com/googleapis/sphinx-docfx-yaml/issues/345. + "sphinxcontrib-applehelp==1.0.4", + "sphinxcontrib-devhelp==1.0.2", + "sphinxcontrib-htmlhelp==2.0.1", + "sphinxcontrib-qthelp==1.0.3", + "sphinxcontrib-serializinghtml==1.1.5", + "gcp-sphinx-docfx-yaml", + "alabaster", + "recommonmark", + ) + + shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) + session.run( + "sphinx-build", + "-T", # show full traceback on exception + "-N", # no colors + "-D", + ( + "extensions=sphinx.ext.autodoc," + "sphinx.ext.autosummary," + "docfx_yaml.extension," + "sphinx.ext.intersphinx," + "sphinx.ext.coverage," + "sphinx.ext.napoleon," + "sphinx.ext.todo," + "sphinx.ext.viewcode," + "recommonmark" + ), + "-b", + "html", + "-d", + os.path.join("docs", "_build", "doctrees", ""), + os.path.join("docs", ""), + os.path.join("docs", "_build", "html", ""), + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +@nox.parametrize( + "protobuf_implementation", + ["python", "upb", "cpp"], +) +def prerelease_deps(session, protobuf_implementation): + """ + Run all tests with pre-release versions of dependencies installed + rather than the standard non pre-release versions. + Pre-release versions can be installed using + `pip install --pre `. + """ + + if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"): + session.skip("cpp implementation is not supported in python 3.11+") + + # Install all dependencies + session.install("-e", ".") + + # Install dependencies for the unit test environment + unit_deps_all = UNIT_TEST_STANDARD_DEPENDENCIES + UNIT_TEST_EXTERNAL_DEPENDENCIES + session.install(*unit_deps_all) + + # Install dependencies for the system test environment + system_deps_all = ( + SYSTEM_TEST_STANDARD_DEPENDENCIES + + SYSTEM_TEST_EXTERNAL_DEPENDENCIES + + SYSTEM_TEST_EXTRAS + ) + session.install(*system_deps_all) + + # Because we test minimum dependency versions on the minimum Python + # version, the first version we test with in the unit tests sessions has a + # constraints file containing all dependencies and extras. + with open( + CURRENT_DIRECTORY / "testing" / f"constraints-{ALL_PYTHON[0]}.txt", + encoding="utf-8", + ) as constraints_file: + constraints_text = constraints_file.read() + + # Ignore leading whitespace and comment lines. + constraints_deps = [ + match.group(1) + for match in re.finditer( + r"^\s*(\S+)(?===\S+)", constraints_text, flags=re.MULTILINE + ) + ] + + # Install dependencies specified in `testing/constraints-X.txt`. + session.install(*constraints_deps) + + # Note: If a dependency is added to the `prerel_deps` list, + # the `core_dependencies_from_source` list in the `core_deps_from_source` + # nox session should also be updated. + prerel_deps = [ + "googleapis-common-protos", + "google-api-core", + "google-auth", + "grpc-google-iam-v1", + "grpcio", + "grpcio-status", + "protobuf", + "proto-plus", + ] + + for dep in prerel_deps: + session.install("--pre", "--no-deps", "--ignore-installed", dep) + # TODO(https://github.com/grpc/grpc/issues/38965): Add `grpcio-status`` + # to the dictionary below once this bug is fixed. + # TODO(https://github.com/googleapis/google-cloud-python/issues/13643): Add + # `googleapis-common-protos` and `grpc-google-iam-v1` to the dictionary below + # once this bug is fixed. + package_namespaces = { + "google-api-core": "google.api_core", + "google-auth": "google.auth", + "grpcio": "grpc", + "protobuf": "google.protobuf", + "proto-plus": "proto", + } + + version_namespace = package_namespaces.get(dep) + + print(f"Installed {dep}") + if version_namespace: + session.run( + "python", + "-c", + f"import {version_namespace}; print({version_namespace}.__version__)", + ) + + session.run( + "py.test", + "tests/unit", + env={ + "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, + }, + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +@nox.parametrize( + "protobuf_implementation", + ["python", "upb"], +) +def core_deps_from_source(session, protobuf_implementation): + """Run all tests with core dependencies installed from source + rather than pulling the dependencies from PyPI. + """ + + # Install all dependencies + session.install("-e", ".") + + # Install dependencies for the unit test environment + unit_deps_all = UNIT_TEST_STANDARD_DEPENDENCIES + UNIT_TEST_EXTERNAL_DEPENDENCIES + session.install(*unit_deps_all) + + # Install dependencies for the system test environment + system_deps_all = ( + SYSTEM_TEST_STANDARD_DEPENDENCIES + + SYSTEM_TEST_EXTERNAL_DEPENDENCIES + + SYSTEM_TEST_EXTRAS + ) + session.install(*system_deps_all) + + # Because we test minimum dependency versions on the minimum Python + # version, the first version we test with in the unit tests sessions has a + # constraints file containing all dependencies and extras. + with open( + CURRENT_DIRECTORY / "testing" / f"constraints-{ALL_PYTHON[0]}.txt", + encoding="utf-8", + ) as constraints_file: + constraints_text = constraints_file.read() + + # Ignore leading whitespace and comment lines. + constraints_deps = [ + match.group(1) + for match in re.finditer( + r"^\s*(\S+)(?===\S+)", constraints_text, flags=re.MULTILINE + ) + ] + + # Install dependencies specified in `testing/constraints-X.txt`. + session.install(*constraints_deps) + + # TODO(https://github.com/googleapis/gapic-generator-python/issues/2358): `grpcio` and + # `grpcio-status` should be added to the list below so that they are installed from source, + # rather than PyPI. + # TODO(https://github.com/googleapis/gapic-generator-python/issues/2357): `protobuf` should be + # added to the list below so that it is installed from source, rather than PyPI + # Note: If a dependency is added to the `core_dependencies_from_source` list, + # the `prerel_deps` list in the `prerelease_deps` nox session should also be updated. + core_dependencies_from_source = [ + "googleapis-common-protos @ git+https://github.com/googleapis/google-cloud-python#egg=googleapis-common-protos&subdirectory=packages/googleapis-common-protos", + "google-api-core @ git+https://github.com/googleapis/python-api-core.git", + "google-auth @ git+https://github.com/googleapis/google-auth-library-python.git", + "grpc-google-iam-v1 @ git+https://github.com/googleapis/google-cloud-python#egg=grpc-google-iam-v1&subdirectory=packages/grpc-google-iam-v1", + "proto-plus @ git+https://github.com/googleapis/proto-plus-python.git", + ] + + for dep in core_dependencies_from_source: + session.install(dep, "--no-deps", "--ignore-installed") + print(f"Installed {dep}") + + session.run( + "py.test", + "tests/unit", + env={ + "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, + }, + ) diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_create_deployment_async.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_create_deployment_async.py new file mode 100644 index 000000000000..3fd5e2cc479c --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_create_deployment_async.py @@ -0,0 +1,61 @@ +# -*- 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 code. DO NOT EDIT! +# +# Snippet for CreateDeployment +# 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-config + + +# [START config_v1_generated_Config_CreateDeployment_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 config_v1 + + +async def sample_create_deployment(): + # Create a client + client = config_v1.ConfigAsyncClient() + + # Initialize request argument(s) + deployment = config_v1.Deployment() + deployment.terraform_blueprint.gcs_source = "gcs_source_value" + + request = config_v1.CreateDeploymentRequest( + parent="parent_value", + deployment_id="deployment_id_value", + deployment=deployment, + ) + + # Make the request + operation = client.create_deployment(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END config_v1_generated_Config_CreateDeployment_async] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_create_deployment_sync.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_create_deployment_sync.py new file mode 100644 index 000000000000..13e926d69c3c --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_create_deployment_sync.py @@ -0,0 +1,61 @@ +# -*- 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 code. DO NOT EDIT! +# +# Snippet for CreateDeployment +# 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-config + + +# [START config_v1_generated_Config_CreateDeployment_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 config_v1 + + +def sample_create_deployment(): + # Create a client + client = config_v1.ConfigClient() + + # Initialize request argument(s) + deployment = config_v1.Deployment() + deployment.terraform_blueprint.gcs_source = "gcs_source_value" + + request = config_v1.CreateDeploymentRequest( + parent="parent_value", + deployment_id="deployment_id_value", + deployment=deployment, + ) + + # Make the request + operation = client.create_deployment(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END config_v1_generated_Config_CreateDeployment_sync] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_create_preview_async.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_create_preview_async.py new file mode 100644 index 000000000000..ae0f1c8ad737 --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_create_preview_async.py @@ -0,0 +1,61 @@ +# -*- 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 code. DO NOT EDIT! +# +# Snippet for CreatePreview +# 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-config + + +# [START config_v1_generated_Config_CreatePreview_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 config_v1 + + +async def sample_create_preview(): + # Create a client + client = config_v1.ConfigAsyncClient() + + # Initialize request argument(s) + preview = config_v1.Preview() + preview.terraform_blueprint.gcs_source = "gcs_source_value" + preview.service_account = "service_account_value" + + request = config_v1.CreatePreviewRequest( + parent="parent_value", + preview=preview, + ) + + # Make the request + operation = client.create_preview(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END config_v1_generated_Config_CreatePreview_async] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_create_preview_sync.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_create_preview_sync.py new file mode 100644 index 000000000000..6a8d6dd8af26 --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_create_preview_sync.py @@ -0,0 +1,61 @@ +# -*- 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 code. DO NOT EDIT! +# +# Snippet for CreatePreview +# 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-config + + +# [START config_v1_generated_Config_CreatePreview_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 config_v1 + + +def sample_create_preview(): + # Create a client + client = config_v1.ConfigClient() + + # Initialize request argument(s) + preview = config_v1.Preview() + preview.terraform_blueprint.gcs_source = "gcs_source_value" + preview.service_account = "service_account_value" + + request = config_v1.CreatePreviewRequest( + parent="parent_value", + preview=preview, + ) + + # Make the request + operation = client.create_preview(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END config_v1_generated_Config_CreatePreview_sync] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_delete_deployment_async.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_delete_deployment_async.py new file mode 100644 index 000000000000..13302b22c1ab --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_delete_deployment_async.py @@ -0,0 +1,56 @@ +# -*- 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 code. DO NOT EDIT! +# +# Snippet for DeleteDeployment +# 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-config + + +# [START config_v1_generated_Config_DeleteDeployment_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 config_v1 + + +async def sample_delete_deployment(): + # Create a client + client = config_v1.ConfigAsyncClient() + + # Initialize request argument(s) + request = config_v1.DeleteDeploymentRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_deployment(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END config_v1_generated_Config_DeleteDeployment_async] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_delete_deployment_sync.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_delete_deployment_sync.py new file mode 100644 index 000000000000..5c3461d83d46 --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_delete_deployment_sync.py @@ -0,0 +1,56 @@ +# -*- 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 code. DO NOT EDIT! +# +# Snippet for DeleteDeployment +# 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-config + + +# [START config_v1_generated_Config_DeleteDeployment_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 config_v1 + + +def sample_delete_deployment(): + # Create a client + client = config_v1.ConfigClient() + + # Initialize request argument(s) + request = config_v1.DeleteDeploymentRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_deployment(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END config_v1_generated_Config_DeleteDeployment_sync] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_delete_preview_async.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_delete_preview_async.py new file mode 100644 index 000000000000..1df8aae40d9e --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_delete_preview_async.py @@ -0,0 +1,56 @@ +# -*- 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 code. DO NOT EDIT! +# +# Snippet for DeletePreview +# 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-config + + +# [START config_v1_generated_Config_DeletePreview_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 config_v1 + + +async def sample_delete_preview(): + # Create a client + client = config_v1.ConfigAsyncClient() + + # Initialize request argument(s) + request = config_v1.DeletePreviewRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_preview(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END config_v1_generated_Config_DeletePreview_async] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_delete_preview_sync.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_delete_preview_sync.py new file mode 100644 index 000000000000..fde6f6cddcb1 --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_delete_preview_sync.py @@ -0,0 +1,56 @@ +# -*- 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 code. DO NOT EDIT! +# +# Snippet for DeletePreview +# 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-config + + +# [START config_v1_generated_Config_DeletePreview_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 config_v1 + + +def sample_delete_preview(): + # Create a client + client = config_v1.ConfigClient() + + # Initialize request argument(s) + request = config_v1.DeletePreviewRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_preview(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END config_v1_generated_Config_DeletePreview_sync] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_delete_statefile_async.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_delete_statefile_async.py new file mode 100644 index 000000000000..fdfd574f8b60 --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_delete_statefile_async.py @@ -0,0 +1,51 @@ +# -*- 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 code. DO NOT EDIT! +# +# Snippet for DeleteStatefile +# 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-config + + +# [START config_v1_generated_Config_DeleteStatefile_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 config_v1 + + +async def sample_delete_statefile(): + # Create a client + client = config_v1.ConfigAsyncClient() + + # Initialize request argument(s) + request = config_v1.DeleteStatefileRequest( + name="name_value", + lock_id=725, + ) + + # Make the request + await client.delete_statefile(request=request) + + +# [END config_v1_generated_Config_DeleteStatefile_async] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_delete_statefile_sync.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_delete_statefile_sync.py new file mode 100644 index 000000000000..c2c686592a1a --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_delete_statefile_sync.py @@ -0,0 +1,51 @@ +# -*- 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 code. DO NOT EDIT! +# +# Snippet for DeleteStatefile +# 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-config + + +# [START config_v1_generated_Config_DeleteStatefile_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 config_v1 + + +def sample_delete_statefile(): + # Create a client + client = config_v1.ConfigClient() + + # Initialize request argument(s) + request = config_v1.DeleteStatefileRequest( + name="name_value", + lock_id=725, + ) + + # Make the request + client.delete_statefile(request=request) + + +# [END config_v1_generated_Config_DeleteStatefile_sync] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_export_deployment_statefile_async.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_export_deployment_statefile_async.py new file mode 100644 index 000000000000..d602d58d6c51 --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_export_deployment_statefile_async.py @@ -0,0 +1,52 @@ +# -*- 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 code. DO NOT EDIT! +# +# Snippet for ExportDeploymentStatefile +# 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-config + + +# [START config_v1_generated_Config_ExportDeploymentStatefile_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 config_v1 + + +async def sample_export_deployment_statefile(): + # Create a client + client = config_v1.ConfigAsyncClient() + + # Initialize request argument(s) + request = config_v1.ExportDeploymentStatefileRequest( + parent="parent_value", + ) + + # Make the request + response = await client.export_deployment_statefile(request=request) + + # Handle the response + print(response) + +# [END config_v1_generated_Config_ExportDeploymentStatefile_async] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_export_deployment_statefile_sync.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_export_deployment_statefile_sync.py new file mode 100644 index 000000000000..6634416cb20a --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_export_deployment_statefile_sync.py @@ -0,0 +1,52 @@ +# -*- 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 code. DO NOT EDIT! +# +# Snippet for ExportDeploymentStatefile +# 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-config + + +# [START config_v1_generated_Config_ExportDeploymentStatefile_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 config_v1 + + +def sample_export_deployment_statefile(): + # Create a client + client = config_v1.ConfigClient() + + # Initialize request argument(s) + request = config_v1.ExportDeploymentStatefileRequest( + parent="parent_value", + ) + + # Make the request + response = client.export_deployment_statefile(request=request) + + # Handle the response + print(response) + +# [END config_v1_generated_Config_ExportDeploymentStatefile_sync] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_export_lock_info_async.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_export_lock_info_async.py new file mode 100644 index 000000000000..5cb010808733 --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_export_lock_info_async.py @@ -0,0 +1,52 @@ +# -*- 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 code. DO NOT EDIT! +# +# Snippet for ExportLockInfo +# 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-config + + +# [START config_v1_generated_Config_ExportLockInfo_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 config_v1 + + +async def sample_export_lock_info(): + # Create a client + client = config_v1.ConfigAsyncClient() + + # Initialize request argument(s) + request = config_v1.ExportLockInfoRequest( + name="name_value", + ) + + # Make the request + response = await client.export_lock_info(request=request) + + # Handle the response + print(response) + +# [END config_v1_generated_Config_ExportLockInfo_async] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_export_lock_info_sync.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_export_lock_info_sync.py new file mode 100644 index 000000000000..cbe67eecd362 --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_export_lock_info_sync.py @@ -0,0 +1,52 @@ +# -*- 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 code. DO NOT EDIT! +# +# Snippet for ExportLockInfo +# 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-config + + +# [START config_v1_generated_Config_ExportLockInfo_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 config_v1 + + +def sample_export_lock_info(): + # Create a client + client = config_v1.ConfigClient() + + # Initialize request argument(s) + request = config_v1.ExportLockInfoRequest( + name="name_value", + ) + + # Make the request + response = client.export_lock_info(request=request) + + # Handle the response + print(response) + +# [END config_v1_generated_Config_ExportLockInfo_sync] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_export_preview_result_async.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_export_preview_result_async.py new file mode 100644 index 000000000000..5343e17a6f7a --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_export_preview_result_async.py @@ -0,0 +1,52 @@ +# -*- 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 code. DO NOT EDIT! +# +# Snippet for ExportPreviewResult +# 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-config + + +# [START config_v1_generated_Config_ExportPreviewResult_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 config_v1 + + +async def sample_export_preview_result(): + # Create a client + client = config_v1.ConfigAsyncClient() + + # Initialize request argument(s) + request = config_v1.ExportPreviewResultRequest( + parent="parent_value", + ) + + # Make the request + response = await client.export_preview_result(request=request) + + # Handle the response + print(response) + +# [END config_v1_generated_Config_ExportPreviewResult_async] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_export_preview_result_sync.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_export_preview_result_sync.py new file mode 100644 index 000000000000..3ef8a42c2272 --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_export_preview_result_sync.py @@ -0,0 +1,52 @@ +# -*- 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 code. DO NOT EDIT! +# +# Snippet for ExportPreviewResult +# 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-config + + +# [START config_v1_generated_Config_ExportPreviewResult_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 config_v1 + + +def sample_export_preview_result(): + # Create a client + client = config_v1.ConfigClient() + + # Initialize request argument(s) + request = config_v1.ExportPreviewResultRequest( + parent="parent_value", + ) + + # Make the request + response = client.export_preview_result(request=request) + + # Handle the response + print(response) + +# [END config_v1_generated_Config_ExportPreviewResult_sync] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_export_revision_statefile_async.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_export_revision_statefile_async.py new file mode 100644 index 000000000000..6297828ad4fb --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_export_revision_statefile_async.py @@ -0,0 +1,52 @@ +# -*- 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 code. DO NOT EDIT! +# +# Snippet for ExportRevisionStatefile +# 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-config + + +# [START config_v1_generated_Config_ExportRevisionStatefile_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 config_v1 + + +async def sample_export_revision_statefile(): + # Create a client + client = config_v1.ConfigAsyncClient() + + # Initialize request argument(s) + request = config_v1.ExportRevisionStatefileRequest( + parent="parent_value", + ) + + # Make the request + response = await client.export_revision_statefile(request=request) + + # Handle the response + print(response) + +# [END config_v1_generated_Config_ExportRevisionStatefile_async] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_export_revision_statefile_sync.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_export_revision_statefile_sync.py new file mode 100644 index 000000000000..2a3eda077104 --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_export_revision_statefile_sync.py @@ -0,0 +1,52 @@ +# -*- 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 code. DO NOT EDIT! +# +# Snippet for ExportRevisionStatefile +# 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-config + + +# [START config_v1_generated_Config_ExportRevisionStatefile_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 config_v1 + + +def sample_export_revision_statefile(): + # Create a client + client = config_v1.ConfigClient() + + # Initialize request argument(s) + request = config_v1.ExportRevisionStatefileRequest( + parent="parent_value", + ) + + # Make the request + response = client.export_revision_statefile(request=request) + + # Handle the response + print(response) + +# [END config_v1_generated_Config_ExportRevisionStatefile_sync] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_deployment_async.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_deployment_async.py new file mode 100644 index 000000000000..db2fdc05e334 --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_deployment_async.py @@ -0,0 +1,52 @@ +# -*- 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 code. DO NOT EDIT! +# +# Snippet for GetDeployment +# 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-config + + +# [START config_v1_generated_Config_GetDeployment_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 config_v1 + + +async def sample_get_deployment(): + # Create a client + client = config_v1.ConfigAsyncClient() + + # Initialize request argument(s) + request = config_v1.GetDeploymentRequest( + name="name_value", + ) + + # Make the request + response = await client.get_deployment(request=request) + + # Handle the response + print(response) + +# [END config_v1_generated_Config_GetDeployment_async] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_deployment_sync.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_deployment_sync.py new file mode 100644 index 000000000000..f25109b58523 --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_deployment_sync.py @@ -0,0 +1,52 @@ +# -*- 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 code. DO NOT EDIT! +# +# Snippet for GetDeployment +# 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-config + + +# [START config_v1_generated_Config_GetDeployment_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 config_v1 + + +def sample_get_deployment(): + # Create a client + client = config_v1.ConfigClient() + + # Initialize request argument(s) + request = config_v1.GetDeploymentRequest( + name="name_value", + ) + + # Make the request + response = client.get_deployment(request=request) + + # Handle the response + print(response) + +# [END config_v1_generated_Config_GetDeployment_sync] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_preview_async.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_preview_async.py new file mode 100644 index 000000000000..fc9d5349b9bc --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_preview_async.py @@ -0,0 +1,52 @@ +# -*- 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 code. DO NOT EDIT! +# +# Snippet for GetPreview +# 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-config + + +# [START config_v1_generated_Config_GetPreview_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 config_v1 + + +async def sample_get_preview(): + # Create a client + client = config_v1.ConfigAsyncClient() + + # Initialize request argument(s) + request = config_v1.GetPreviewRequest( + name="name_value", + ) + + # Make the request + response = await client.get_preview(request=request) + + # Handle the response + print(response) + +# [END config_v1_generated_Config_GetPreview_async] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_preview_sync.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_preview_sync.py new file mode 100644 index 000000000000..cb569e2fee4a --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_preview_sync.py @@ -0,0 +1,52 @@ +# -*- 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 code. DO NOT EDIT! +# +# Snippet for GetPreview +# 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-config + + +# [START config_v1_generated_Config_GetPreview_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 config_v1 + + +def sample_get_preview(): + # Create a client + client = config_v1.ConfigClient() + + # Initialize request argument(s) + request = config_v1.GetPreviewRequest( + name="name_value", + ) + + # Make the request + response = client.get_preview(request=request) + + # Handle the response + print(response) + +# [END config_v1_generated_Config_GetPreview_sync] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_resource_async.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_resource_async.py new file mode 100644 index 000000000000..0da5b8a568bf --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_resource_async.py @@ -0,0 +1,52 @@ +# -*- 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 code. DO NOT EDIT! +# +# Snippet for GetResource +# 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-config + + +# [START config_v1_generated_Config_GetResource_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 config_v1 + + +async def sample_get_resource(): + # Create a client + client = config_v1.ConfigAsyncClient() + + # Initialize request argument(s) + request = config_v1.GetResourceRequest( + name="name_value", + ) + + # Make the request + response = await client.get_resource(request=request) + + # Handle the response + print(response) + +# [END config_v1_generated_Config_GetResource_async] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_resource_change_async.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_resource_change_async.py new file mode 100644 index 000000000000..e5ae15f06e73 --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_resource_change_async.py @@ -0,0 +1,52 @@ +# -*- 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 code. DO NOT EDIT! +# +# Snippet for GetResourceChange +# 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-config + + +# [START config_v1_generated_Config_GetResourceChange_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 config_v1 + + +async def sample_get_resource_change(): + # Create a client + client = config_v1.ConfigAsyncClient() + + # Initialize request argument(s) + request = config_v1.GetResourceChangeRequest( + name="name_value", + ) + + # Make the request + response = await client.get_resource_change(request=request) + + # Handle the response + print(response) + +# [END config_v1_generated_Config_GetResourceChange_async] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_resource_change_sync.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_resource_change_sync.py new file mode 100644 index 000000000000..9d9f76af84ab --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_resource_change_sync.py @@ -0,0 +1,52 @@ +# -*- 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 code. DO NOT EDIT! +# +# Snippet for GetResourceChange +# 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-config + + +# [START config_v1_generated_Config_GetResourceChange_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 config_v1 + + +def sample_get_resource_change(): + # Create a client + client = config_v1.ConfigClient() + + # Initialize request argument(s) + request = config_v1.GetResourceChangeRequest( + name="name_value", + ) + + # Make the request + response = client.get_resource_change(request=request) + + # Handle the response + print(response) + +# [END config_v1_generated_Config_GetResourceChange_sync] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_resource_drift_async.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_resource_drift_async.py new file mode 100644 index 000000000000..3383906e899f --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_resource_drift_async.py @@ -0,0 +1,52 @@ +# -*- 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 code. DO NOT EDIT! +# +# Snippet for GetResourceDrift +# 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-config + + +# [START config_v1_generated_Config_GetResourceDrift_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 config_v1 + + +async def sample_get_resource_drift(): + # Create a client + client = config_v1.ConfigAsyncClient() + + # Initialize request argument(s) + request = config_v1.GetResourceDriftRequest( + name="name_value", + ) + + # Make the request + response = await client.get_resource_drift(request=request) + + # Handle the response + print(response) + +# [END config_v1_generated_Config_GetResourceDrift_async] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_resource_drift_sync.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_resource_drift_sync.py new file mode 100644 index 000000000000..0747cff56542 --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_resource_drift_sync.py @@ -0,0 +1,52 @@ +# -*- 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 code. DO NOT EDIT! +# +# Snippet for GetResourceDrift +# 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-config + + +# [START config_v1_generated_Config_GetResourceDrift_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 config_v1 + + +def sample_get_resource_drift(): + # Create a client + client = config_v1.ConfigClient() + + # Initialize request argument(s) + request = config_v1.GetResourceDriftRequest( + name="name_value", + ) + + # Make the request + response = client.get_resource_drift(request=request) + + # Handle the response + print(response) + +# [END config_v1_generated_Config_GetResourceDrift_sync] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_resource_sync.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_resource_sync.py new file mode 100644 index 000000000000..daa073ed2aca --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_resource_sync.py @@ -0,0 +1,52 @@ +# -*- 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 code. DO NOT EDIT! +# +# Snippet for GetResource +# 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-config + + +# [START config_v1_generated_Config_GetResource_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 config_v1 + + +def sample_get_resource(): + # Create a client + client = config_v1.ConfigClient() + + # Initialize request argument(s) + request = config_v1.GetResourceRequest( + name="name_value", + ) + + # Make the request + response = client.get_resource(request=request) + + # Handle the response + print(response) + +# [END config_v1_generated_Config_GetResource_sync] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_revision_async.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_revision_async.py new file mode 100644 index 000000000000..57d693b81926 --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_revision_async.py @@ -0,0 +1,52 @@ +# -*- 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 code. DO NOT EDIT! +# +# Snippet for GetRevision +# 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-config + + +# [START config_v1_generated_Config_GetRevision_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 config_v1 + + +async def sample_get_revision(): + # Create a client + client = config_v1.ConfigAsyncClient() + + # Initialize request argument(s) + request = config_v1.GetRevisionRequest( + name="name_value", + ) + + # Make the request + response = await client.get_revision(request=request) + + # Handle the response + print(response) + +# [END config_v1_generated_Config_GetRevision_async] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_revision_sync.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_revision_sync.py new file mode 100644 index 000000000000..98996604e6ac --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_revision_sync.py @@ -0,0 +1,52 @@ +# -*- 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 code. DO NOT EDIT! +# +# Snippet for GetRevision +# 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-config + + +# [START config_v1_generated_Config_GetRevision_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 config_v1 + + +def sample_get_revision(): + # Create a client + client = config_v1.ConfigClient() + + # Initialize request argument(s) + request = config_v1.GetRevisionRequest( + name="name_value", + ) + + # Make the request + response = client.get_revision(request=request) + + # Handle the response + print(response) + +# [END config_v1_generated_Config_GetRevision_sync] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_terraform_version_async.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_terraform_version_async.py new file mode 100644 index 000000000000..b7529c444505 --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_terraform_version_async.py @@ -0,0 +1,52 @@ +# -*- 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 code. DO NOT EDIT! +# +# Snippet for GetTerraformVersion +# 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-config + + +# [START config_v1_generated_Config_GetTerraformVersion_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 config_v1 + + +async def sample_get_terraform_version(): + # Create a client + client = config_v1.ConfigAsyncClient() + + # Initialize request argument(s) + request = config_v1.GetTerraformVersionRequest( + name="name_value", + ) + + # Make the request + response = await client.get_terraform_version(request=request) + + # Handle the response + print(response) + +# [END config_v1_generated_Config_GetTerraformVersion_async] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_terraform_version_sync.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_terraform_version_sync.py new file mode 100644 index 000000000000..83ed8de8a446 --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_terraform_version_sync.py @@ -0,0 +1,52 @@ +# -*- 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 code. DO NOT EDIT! +# +# Snippet for GetTerraformVersion +# 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-config + + +# [START config_v1_generated_Config_GetTerraformVersion_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 config_v1 + + +def sample_get_terraform_version(): + # Create a client + client = config_v1.ConfigClient() + + # Initialize request argument(s) + request = config_v1.GetTerraformVersionRequest( + name="name_value", + ) + + # Make the request + response = client.get_terraform_version(request=request) + + # Handle the response + print(response) + +# [END config_v1_generated_Config_GetTerraformVersion_sync] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_import_statefile_async.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_import_statefile_async.py new file mode 100644 index 000000000000..f12777fe9b39 --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_import_statefile_async.py @@ -0,0 +1,53 @@ +# -*- 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 code. DO NOT EDIT! +# +# Snippet for ImportStatefile +# 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-config + + +# [START config_v1_generated_Config_ImportStatefile_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 config_v1 + + +async def sample_import_statefile(): + # Create a client + client = config_v1.ConfigAsyncClient() + + # Initialize request argument(s) + request = config_v1.ImportStatefileRequest( + parent="parent_value", + lock_id=725, + ) + + # Make the request + response = await client.import_statefile(request=request) + + # Handle the response + print(response) + +# [END config_v1_generated_Config_ImportStatefile_async] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_import_statefile_sync.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_import_statefile_sync.py new file mode 100644 index 000000000000..13b7deffff7a --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_import_statefile_sync.py @@ -0,0 +1,53 @@ +# -*- 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 code. DO NOT EDIT! +# +# Snippet for ImportStatefile +# 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-config + + +# [START config_v1_generated_Config_ImportStatefile_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 config_v1 + + +def sample_import_statefile(): + # Create a client + client = config_v1.ConfigClient() + + # Initialize request argument(s) + request = config_v1.ImportStatefileRequest( + parent="parent_value", + lock_id=725, + ) + + # Make the request + response = client.import_statefile(request=request) + + # Handle the response + print(response) + +# [END config_v1_generated_Config_ImportStatefile_sync] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_deployments_async.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_deployments_async.py new file mode 100644 index 000000000000..e854d0b85cb8 --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_deployments_async.py @@ -0,0 +1,53 @@ +# -*- 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 code. DO NOT EDIT! +# +# Snippet for ListDeployments +# 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-config + + +# [START config_v1_generated_Config_ListDeployments_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 config_v1 + + +async def sample_list_deployments(): + # Create a client + client = config_v1.ConfigAsyncClient() + + # Initialize request argument(s) + request = config_v1.ListDeploymentsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_deployments(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END config_v1_generated_Config_ListDeployments_async] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_deployments_sync.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_deployments_sync.py new file mode 100644 index 000000000000..963621cb81f2 --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_deployments_sync.py @@ -0,0 +1,53 @@ +# -*- 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 code. DO NOT EDIT! +# +# Snippet for ListDeployments +# 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-config + + +# [START config_v1_generated_Config_ListDeployments_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 config_v1 + + +def sample_list_deployments(): + # Create a client + client = config_v1.ConfigClient() + + # Initialize request argument(s) + request = config_v1.ListDeploymentsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_deployments(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END config_v1_generated_Config_ListDeployments_sync] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_previews_async.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_previews_async.py new file mode 100644 index 000000000000..42602ac89455 --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_previews_async.py @@ -0,0 +1,53 @@ +# -*- 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 code. DO NOT EDIT! +# +# Snippet for ListPreviews +# 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-config + + +# [START config_v1_generated_Config_ListPreviews_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 config_v1 + + +async def sample_list_previews(): + # Create a client + client = config_v1.ConfigAsyncClient() + + # Initialize request argument(s) + request = config_v1.ListPreviewsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_previews(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END config_v1_generated_Config_ListPreviews_async] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_previews_sync.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_previews_sync.py new file mode 100644 index 000000000000..a600f538aaa8 --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_previews_sync.py @@ -0,0 +1,53 @@ +# -*- 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 code. DO NOT EDIT! +# +# Snippet for ListPreviews +# 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-config + + +# [START config_v1_generated_Config_ListPreviews_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 config_v1 + + +def sample_list_previews(): + # Create a client + client = config_v1.ConfigClient() + + # Initialize request argument(s) + request = config_v1.ListPreviewsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_previews(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END config_v1_generated_Config_ListPreviews_sync] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_resource_changes_async.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_resource_changes_async.py new file mode 100644 index 000000000000..9d6aa11137f8 --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_resource_changes_async.py @@ -0,0 +1,53 @@ +# -*- 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 code. DO NOT EDIT! +# +# Snippet for ListResourceChanges +# 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-config + + +# [START config_v1_generated_Config_ListResourceChanges_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 config_v1 + + +async def sample_list_resource_changes(): + # Create a client + client = config_v1.ConfigAsyncClient() + + # Initialize request argument(s) + request = config_v1.ListResourceChangesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_resource_changes(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END config_v1_generated_Config_ListResourceChanges_async] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_resource_changes_sync.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_resource_changes_sync.py new file mode 100644 index 000000000000..28df72a2c143 --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_resource_changes_sync.py @@ -0,0 +1,53 @@ +# -*- 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 code. DO NOT EDIT! +# +# Snippet for ListResourceChanges +# 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-config + + +# [START config_v1_generated_Config_ListResourceChanges_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 config_v1 + + +def sample_list_resource_changes(): + # Create a client + client = config_v1.ConfigClient() + + # Initialize request argument(s) + request = config_v1.ListResourceChangesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_resource_changes(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END config_v1_generated_Config_ListResourceChanges_sync] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_resource_drifts_async.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_resource_drifts_async.py new file mode 100644 index 000000000000..3ae0be582ae2 --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_resource_drifts_async.py @@ -0,0 +1,53 @@ +# -*- 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 code. DO NOT EDIT! +# +# Snippet for ListResourceDrifts +# 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-config + + +# [START config_v1_generated_Config_ListResourceDrifts_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 config_v1 + + +async def sample_list_resource_drifts(): + # Create a client + client = config_v1.ConfigAsyncClient() + + # Initialize request argument(s) + request = config_v1.ListResourceDriftsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_resource_drifts(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END config_v1_generated_Config_ListResourceDrifts_async] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_resource_drifts_sync.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_resource_drifts_sync.py new file mode 100644 index 000000000000..46370dc55987 --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_resource_drifts_sync.py @@ -0,0 +1,53 @@ +# -*- 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 code. DO NOT EDIT! +# +# Snippet for ListResourceDrifts +# 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-config + + +# [START config_v1_generated_Config_ListResourceDrifts_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 config_v1 + + +def sample_list_resource_drifts(): + # Create a client + client = config_v1.ConfigClient() + + # Initialize request argument(s) + request = config_v1.ListResourceDriftsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_resource_drifts(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END config_v1_generated_Config_ListResourceDrifts_sync] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_resources_async.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_resources_async.py new file mode 100644 index 000000000000..3dcf01ff5411 --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_resources_async.py @@ -0,0 +1,53 @@ +# -*- 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 code. DO NOT EDIT! +# +# Snippet for ListResources +# 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-config + + +# [START config_v1_generated_Config_ListResources_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 config_v1 + + +async def sample_list_resources(): + # Create a client + client = config_v1.ConfigAsyncClient() + + # Initialize request argument(s) + request = config_v1.ListResourcesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_resources(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END config_v1_generated_Config_ListResources_async] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_resources_sync.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_resources_sync.py new file mode 100644 index 000000000000..1846ee47b345 --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_resources_sync.py @@ -0,0 +1,53 @@ +# -*- 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 code. DO NOT EDIT! +# +# Snippet for ListResources +# 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-config + + +# [START config_v1_generated_Config_ListResources_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 config_v1 + + +def sample_list_resources(): + # Create a client + client = config_v1.ConfigClient() + + # Initialize request argument(s) + request = config_v1.ListResourcesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_resources(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END config_v1_generated_Config_ListResources_sync] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_revisions_async.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_revisions_async.py new file mode 100644 index 000000000000..3ae25389e89d --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_revisions_async.py @@ -0,0 +1,53 @@ +# -*- 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 code. DO NOT EDIT! +# +# Snippet for ListRevisions +# 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-config + + +# [START config_v1_generated_Config_ListRevisions_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 config_v1 + + +async def sample_list_revisions(): + # Create a client + client = config_v1.ConfigAsyncClient() + + # Initialize request argument(s) + request = config_v1.ListRevisionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_revisions(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END config_v1_generated_Config_ListRevisions_async] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_revisions_sync.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_revisions_sync.py new file mode 100644 index 000000000000..8ac8caa1aa6b --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_revisions_sync.py @@ -0,0 +1,53 @@ +# -*- 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 code. DO NOT EDIT! +# +# Snippet for ListRevisions +# 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-config + + +# [START config_v1_generated_Config_ListRevisions_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 config_v1 + + +def sample_list_revisions(): + # Create a client + client = config_v1.ConfigClient() + + # Initialize request argument(s) + request = config_v1.ListRevisionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_revisions(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END config_v1_generated_Config_ListRevisions_sync] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_terraform_versions_async.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_terraform_versions_async.py new file mode 100644 index 000000000000..eacac7c01eec --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_terraform_versions_async.py @@ -0,0 +1,53 @@ +# -*- 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 code. DO NOT EDIT! +# +# Snippet for ListTerraformVersions +# 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-config + + +# [START config_v1_generated_Config_ListTerraformVersions_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 config_v1 + + +async def sample_list_terraform_versions(): + # Create a client + client = config_v1.ConfigAsyncClient() + + # Initialize request argument(s) + request = config_v1.ListTerraformVersionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_terraform_versions(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END config_v1_generated_Config_ListTerraformVersions_async] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_terraform_versions_sync.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_terraform_versions_sync.py new file mode 100644 index 000000000000..127610432e1d --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_terraform_versions_sync.py @@ -0,0 +1,53 @@ +# -*- 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 code. DO NOT EDIT! +# +# Snippet for ListTerraformVersions +# 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-config + + +# [START config_v1_generated_Config_ListTerraformVersions_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 config_v1 + + +def sample_list_terraform_versions(): + # Create a client + client = config_v1.ConfigClient() + + # Initialize request argument(s) + request = config_v1.ListTerraformVersionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_terraform_versions(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END config_v1_generated_Config_ListTerraformVersions_sync] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_lock_deployment_async.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_lock_deployment_async.py new file mode 100644 index 000000000000..53b5509a1ce3 --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_lock_deployment_async.py @@ -0,0 +1,56 @@ +# -*- 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 code. DO NOT EDIT! +# +# Snippet for LockDeployment +# 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-config + + +# [START config_v1_generated_Config_LockDeployment_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 config_v1 + + +async def sample_lock_deployment(): + # Create a client + client = config_v1.ConfigAsyncClient() + + # Initialize request argument(s) + request = config_v1.LockDeploymentRequest( + name="name_value", + ) + + # Make the request + operation = client.lock_deployment(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END config_v1_generated_Config_LockDeployment_async] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_lock_deployment_sync.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_lock_deployment_sync.py new file mode 100644 index 000000000000..1fbf51737107 --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_lock_deployment_sync.py @@ -0,0 +1,56 @@ +# -*- 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 code. DO NOT EDIT! +# +# Snippet for LockDeployment +# 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-config + + +# [START config_v1_generated_Config_LockDeployment_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 config_v1 + + +def sample_lock_deployment(): + # Create a client + client = config_v1.ConfigClient() + + # Initialize request argument(s) + request = config_v1.LockDeploymentRequest( + name="name_value", + ) + + # Make the request + operation = client.lock_deployment(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END config_v1_generated_Config_LockDeployment_sync] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_unlock_deployment_async.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_unlock_deployment_async.py new file mode 100644 index 000000000000..c332f1cfb950 --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_unlock_deployment_async.py @@ -0,0 +1,57 @@ +# -*- 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 code. DO NOT EDIT! +# +# Snippet for UnlockDeployment +# 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-config + + +# [START config_v1_generated_Config_UnlockDeployment_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 config_v1 + + +async def sample_unlock_deployment(): + # Create a client + client = config_v1.ConfigAsyncClient() + + # Initialize request argument(s) + request = config_v1.UnlockDeploymentRequest( + name="name_value", + lock_id=725, + ) + + # Make the request + operation = client.unlock_deployment(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END config_v1_generated_Config_UnlockDeployment_async] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_unlock_deployment_sync.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_unlock_deployment_sync.py new file mode 100644 index 000000000000..2ce243fe0ef2 --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_unlock_deployment_sync.py @@ -0,0 +1,57 @@ +# -*- 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 code. DO NOT EDIT! +# +# Snippet for UnlockDeployment +# 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-config + + +# [START config_v1_generated_Config_UnlockDeployment_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 config_v1 + + +def sample_unlock_deployment(): + # Create a client + client = config_v1.ConfigClient() + + # Initialize request argument(s) + request = config_v1.UnlockDeploymentRequest( + name="name_value", + lock_id=725, + ) + + # Make the request + operation = client.unlock_deployment(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END config_v1_generated_Config_UnlockDeployment_sync] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_update_deployment_async.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_update_deployment_async.py new file mode 100644 index 000000000000..8961f5f2d773 --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_update_deployment_async.py @@ -0,0 +1,59 @@ +# -*- 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 code. DO NOT EDIT! +# +# Snippet for UpdateDeployment +# 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-config + + +# [START config_v1_generated_Config_UpdateDeployment_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 config_v1 + + +async def sample_update_deployment(): + # Create a client + client = config_v1.ConfigAsyncClient() + + # Initialize request argument(s) + deployment = config_v1.Deployment() + deployment.terraform_blueprint.gcs_source = "gcs_source_value" + + request = config_v1.UpdateDeploymentRequest( + deployment=deployment, + ) + + # Make the request + operation = client.update_deployment(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END config_v1_generated_Config_UpdateDeployment_async] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_update_deployment_sync.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_update_deployment_sync.py new file mode 100644 index 000000000000..72639735ea78 --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_update_deployment_sync.py @@ -0,0 +1,59 @@ +# -*- 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 code. DO NOT EDIT! +# +# Snippet for UpdateDeployment +# 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-config + + +# [START config_v1_generated_Config_UpdateDeployment_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 config_v1 + + +def sample_update_deployment(): + # Create a client + client = config_v1.ConfigClient() + + # Initialize request argument(s) + deployment = config_v1.Deployment() + deployment.terraform_blueprint.gcs_source = "gcs_source_value" + + request = config_v1.UpdateDeploymentRequest( + deployment=deployment, + ) + + # Make the request + operation = client.update_deployment(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END config_v1_generated_Config_UpdateDeployment_sync] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/snippet_metadata_google.cloud.config.v1.json b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/snippet_metadata_google.cloud.config.v1.json new file mode 100644 index 000000000000..8a55b66d4f2f --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/snippet_metadata_google.cloud.config.v1.json @@ -0,0 +1,4380 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.cloud.config.v1", + "version": "v1" + } + ], + "language": "PYTHON", + "name": "google-cloud-config", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.config_v1.ConfigAsyncClient", + "shortName": "ConfigAsyncClient" + }, + "fullName": "google.cloud.config_v1.ConfigAsyncClient.create_deployment", + "method": { + "fullName": "google.cloud.config.v1.Config.CreateDeployment", + "service": { + "fullName": "google.cloud.config.v1.Config", + "shortName": "Config" + }, + "shortName": "CreateDeployment" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.config_v1.types.CreateDeploymentRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "deployment", + "type": "google.cloud.config_v1.types.Deployment" + }, + { + "name": "deployment_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_deployment" + }, + "description": "Sample for CreateDeployment", + "file": "config_v1_generated_config_create_deployment_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "config_v1_generated_Config_CreateDeployment_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": "config_v1_generated_config_create_deployment_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.config_v1.ConfigClient", + "shortName": "ConfigClient" + }, + "fullName": "google.cloud.config_v1.ConfigClient.create_deployment", + "method": { + "fullName": "google.cloud.config.v1.Config.CreateDeployment", + "service": { + "fullName": "google.cloud.config.v1.Config", + "shortName": "Config" + }, + "shortName": "CreateDeployment" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.config_v1.types.CreateDeploymentRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "deployment", + "type": "google.cloud.config_v1.types.Deployment" + }, + { + "name": "deployment_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_deployment" + }, + "description": "Sample for CreateDeployment", + "file": "config_v1_generated_config_create_deployment_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "config_v1_generated_Config_CreateDeployment_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": "config_v1_generated_config_create_deployment_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.config_v1.ConfigAsyncClient", + "shortName": "ConfigAsyncClient" + }, + "fullName": "google.cloud.config_v1.ConfigAsyncClient.create_preview", + "method": { + "fullName": "google.cloud.config.v1.Config.CreatePreview", + "service": { + "fullName": "google.cloud.config.v1.Config", + "shortName": "Config" + }, + "shortName": "CreatePreview" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.config_v1.types.CreatePreviewRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "preview", + "type": "google.cloud.config_v1.types.Preview" + }, + { + "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_preview" + }, + "description": "Sample for CreatePreview", + "file": "config_v1_generated_config_create_preview_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "config_v1_generated_Config_CreatePreview_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": "config_v1_generated_config_create_preview_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.config_v1.ConfigClient", + "shortName": "ConfigClient" + }, + "fullName": "google.cloud.config_v1.ConfigClient.create_preview", + "method": { + "fullName": "google.cloud.config.v1.Config.CreatePreview", + "service": { + "fullName": "google.cloud.config.v1.Config", + "shortName": "Config" + }, + "shortName": "CreatePreview" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.config_v1.types.CreatePreviewRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "preview", + "type": "google.cloud.config_v1.types.Preview" + }, + { + "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_preview" + }, + "description": "Sample for CreatePreview", + "file": "config_v1_generated_config_create_preview_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "config_v1_generated_Config_CreatePreview_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": "config_v1_generated_config_create_preview_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.config_v1.ConfigAsyncClient", + "shortName": "ConfigAsyncClient" + }, + "fullName": "google.cloud.config_v1.ConfigAsyncClient.delete_deployment", + "method": { + "fullName": "google.cloud.config.v1.Config.DeleteDeployment", + "service": { + "fullName": "google.cloud.config.v1.Config", + "shortName": "Config" + }, + "shortName": "DeleteDeployment" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.config_v1.types.DeleteDeploymentRequest" + }, + { + "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_deployment" + }, + "description": "Sample for DeleteDeployment", + "file": "config_v1_generated_config_delete_deployment_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "config_v1_generated_Config_DeleteDeployment_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": "config_v1_generated_config_delete_deployment_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.config_v1.ConfigClient", + "shortName": "ConfigClient" + }, + "fullName": "google.cloud.config_v1.ConfigClient.delete_deployment", + "method": { + "fullName": "google.cloud.config.v1.Config.DeleteDeployment", + "service": { + "fullName": "google.cloud.config.v1.Config", + "shortName": "Config" + }, + "shortName": "DeleteDeployment" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.config_v1.types.DeleteDeploymentRequest" + }, + { + "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_deployment" + }, + "description": "Sample for DeleteDeployment", + "file": "config_v1_generated_config_delete_deployment_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "config_v1_generated_Config_DeleteDeployment_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": "config_v1_generated_config_delete_deployment_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.config_v1.ConfigAsyncClient", + "shortName": "ConfigAsyncClient" + }, + "fullName": "google.cloud.config_v1.ConfigAsyncClient.delete_preview", + "method": { + "fullName": "google.cloud.config.v1.Config.DeletePreview", + "service": { + "fullName": "google.cloud.config.v1.Config", + "shortName": "Config" + }, + "shortName": "DeletePreview" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.config_v1.types.DeletePreviewRequest" + }, + { + "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_preview" + }, + "description": "Sample for DeletePreview", + "file": "config_v1_generated_config_delete_preview_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "config_v1_generated_Config_DeletePreview_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": "config_v1_generated_config_delete_preview_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.config_v1.ConfigClient", + "shortName": "ConfigClient" + }, + "fullName": "google.cloud.config_v1.ConfigClient.delete_preview", + "method": { + "fullName": "google.cloud.config.v1.Config.DeletePreview", + "service": { + "fullName": "google.cloud.config.v1.Config", + "shortName": "Config" + }, + "shortName": "DeletePreview" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.config_v1.types.DeletePreviewRequest" + }, + { + "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_preview" + }, + "description": "Sample for DeletePreview", + "file": "config_v1_generated_config_delete_preview_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "config_v1_generated_Config_DeletePreview_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": "config_v1_generated_config_delete_preview_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.config_v1.ConfigAsyncClient", + "shortName": "ConfigAsyncClient" + }, + "fullName": "google.cloud.config_v1.ConfigAsyncClient.delete_statefile", + "method": { + "fullName": "google.cloud.config.v1.Config.DeleteStatefile", + "service": { + "fullName": "google.cloud.config.v1.Config", + "shortName": "Config" + }, + "shortName": "DeleteStatefile" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.config_v1.types.DeleteStatefileRequest" + }, + { + "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_statefile" + }, + "description": "Sample for DeleteStatefile", + "file": "config_v1_generated_config_delete_statefile_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "config_v1_generated_Config_DeleteStatefile_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "config_v1_generated_config_delete_statefile_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.config_v1.ConfigClient", + "shortName": "ConfigClient" + }, + "fullName": "google.cloud.config_v1.ConfigClient.delete_statefile", + "method": { + "fullName": "google.cloud.config.v1.Config.DeleteStatefile", + "service": { + "fullName": "google.cloud.config.v1.Config", + "shortName": "Config" + }, + "shortName": "DeleteStatefile" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.config_v1.types.DeleteStatefileRequest" + }, + { + "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_statefile" + }, + "description": "Sample for DeleteStatefile", + "file": "config_v1_generated_config_delete_statefile_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "config_v1_generated_Config_DeleteStatefile_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "config_v1_generated_config_delete_statefile_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.config_v1.ConfigAsyncClient", + "shortName": "ConfigAsyncClient" + }, + "fullName": "google.cloud.config_v1.ConfigAsyncClient.export_deployment_statefile", + "method": { + "fullName": "google.cloud.config.v1.Config.ExportDeploymentStatefile", + "service": { + "fullName": "google.cloud.config.v1.Config", + "shortName": "Config" + }, + "shortName": "ExportDeploymentStatefile" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.config_v1.types.ExportDeploymentStatefileRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.config_v1.types.Statefile", + "shortName": "export_deployment_statefile" + }, + "description": "Sample for ExportDeploymentStatefile", + "file": "config_v1_generated_config_export_deployment_statefile_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "config_v1_generated_Config_ExportDeploymentStatefile_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": "config_v1_generated_config_export_deployment_statefile_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.config_v1.ConfigClient", + "shortName": "ConfigClient" + }, + "fullName": "google.cloud.config_v1.ConfigClient.export_deployment_statefile", + "method": { + "fullName": "google.cloud.config.v1.Config.ExportDeploymentStatefile", + "service": { + "fullName": "google.cloud.config.v1.Config", + "shortName": "Config" + }, + "shortName": "ExportDeploymentStatefile" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.config_v1.types.ExportDeploymentStatefileRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.config_v1.types.Statefile", + "shortName": "export_deployment_statefile" + }, + "description": "Sample for ExportDeploymentStatefile", + "file": "config_v1_generated_config_export_deployment_statefile_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "config_v1_generated_Config_ExportDeploymentStatefile_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": "config_v1_generated_config_export_deployment_statefile_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.config_v1.ConfigAsyncClient", + "shortName": "ConfigAsyncClient" + }, + "fullName": "google.cloud.config_v1.ConfigAsyncClient.export_lock_info", + "method": { + "fullName": "google.cloud.config.v1.Config.ExportLockInfo", + "service": { + "fullName": "google.cloud.config.v1.Config", + "shortName": "Config" + }, + "shortName": "ExportLockInfo" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.config_v1.types.ExportLockInfoRequest" + }, + { + "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.config_v1.types.LockInfo", + "shortName": "export_lock_info" + }, + "description": "Sample for ExportLockInfo", + "file": "config_v1_generated_config_export_lock_info_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "config_v1_generated_Config_ExportLockInfo_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": "config_v1_generated_config_export_lock_info_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.config_v1.ConfigClient", + "shortName": "ConfigClient" + }, + "fullName": "google.cloud.config_v1.ConfigClient.export_lock_info", + "method": { + "fullName": "google.cloud.config.v1.Config.ExportLockInfo", + "service": { + "fullName": "google.cloud.config.v1.Config", + "shortName": "Config" + }, + "shortName": "ExportLockInfo" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.config_v1.types.ExportLockInfoRequest" + }, + { + "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.config_v1.types.LockInfo", + "shortName": "export_lock_info" + }, + "description": "Sample for ExportLockInfo", + "file": "config_v1_generated_config_export_lock_info_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "config_v1_generated_Config_ExportLockInfo_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": "config_v1_generated_config_export_lock_info_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.config_v1.ConfigAsyncClient", + "shortName": "ConfigAsyncClient" + }, + "fullName": "google.cloud.config_v1.ConfigAsyncClient.export_preview_result", + "method": { + "fullName": "google.cloud.config.v1.Config.ExportPreviewResult", + "service": { + "fullName": "google.cloud.config.v1.Config", + "shortName": "Config" + }, + "shortName": "ExportPreviewResult" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.config_v1.types.ExportPreviewResultRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.config_v1.types.ExportPreviewResultResponse", + "shortName": "export_preview_result" + }, + "description": "Sample for ExportPreviewResult", + "file": "config_v1_generated_config_export_preview_result_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "config_v1_generated_Config_ExportPreviewResult_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": "config_v1_generated_config_export_preview_result_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.config_v1.ConfigClient", + "shortName": "ConfigClient" + }, + "fullName": "google.cloud.config_v1.ConfigClient.export_preview_result", + "method": { + "fullName": "google.cloud.config.v1.Config.ExportPreviewResult", + "service": { + "fullName": "google.cloud.config.v1.Config", + "shortName": "Config" + }, + "shortName": "ExportPreviewResult" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.config_v1.types.ExportPreviewResultRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.config_v1.types.ExportPreviewResultResponse", + "shortName": "export_preview_result" + }, + "description": "Sample for ExportPreviewResult", + "file": "config_v1_generated_config_export_preview_result_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "config_v1_generated_Config_ExportPreviewResult_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": "config_v1_generated_config_export_preview_result_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.config_v1.ConfigAsyncClient", + "shortName": "ConfigAsyncClient" + }, + "fullName": "google.cloud.config_v1.ConfigAsyncClient.export_revision_statefile", + "method": { + "fullName": "google.cloud.config.v1.Config.ExportRevisionStatefile", + "service": { + "fullName": "google.cloud.config.v1.Config", + "shortName": "Config" + }, + "shortName": "ExportRevisionStatefile" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.config_v1.types.ExportRevisionStatefileRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.config_v1.types.Statefile", + "shortName": "export_revision_statefile" + }, + "description": "Sample for ExportRevisionStatefile", + "file": "config_v1_generated_config_export_revision_statefile_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "config_v1_generated_Config_ExportRevisionStatefile_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": "config_v1_generated_config_export_revision_statefile_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.config_v1.ConfigClient", + "shortName": "ConfigClient" + }, + "fullName": "google.cloud.config_v1.ConfigClient.export_revision_statefile", + "method": { + "fullName": "google.cloud.config.v1.Config.ExportRevisionStatefile", + "service": { + "fullName": "google.cloud.config.v1.Config", + "shortName": "Config" + }, + "shortName": "ExportRevisionStatefile" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.config_v1.types.ExportRevisionStatefileRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.config_v1.types.Statefile", + "shortName": "export_revision_statefile" + }, + "description": "Sample for ExportRevisionStatefile", + "file": "config_v1_generated_config_export_revision_statefile_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "config_v1_generated_Config_ExportRevisionStatefile_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": "config_v1_generated_config_export_revision_statefile_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.config_v1.ConfigAsyncClient", + "shortName": "ConfigAsyncClient" + }, + "fullName": "google.cloud.config_v1.ConfigAsyncClient.get_deployment", + "method": { + "fullName": "google.cloud.config.v1.Config.GetDeployment", + "service": { + "fullName": "google.cloud.config.v1.Config", + "shortName": "Config" + }, + "shortName": "GetDeployment" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.config_v1.types.GetDeploymentRequest" + }, + { + "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.config_v1.types.Deployment", + "shortName": "get_deployment" + }, + "description": "Sample for GetDeployment", + "file": "config_v1_generated_config_get_deployment_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "config_v1_generated_Config_GetDeployment_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": "config_v1_generated_config_get_deployment_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.config_v1.ConfigClient", + "shortName": "ConfigClient" + }, + "fullName": "google.cloud.config_v1.ConfigClient.get_deployment", + "method": { + "fullName": "google.cloud.config.v1.Config.GetDeployment", + "service": { + "fullName": "google.cloud.config.v1.Config", + "shortName": "Config" + }, + "shortName": "GetDeployment" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.config_v1.types.GetDeploymentRequest" + }, + { + "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.config_v1.types.Deployment", + "shortName": "get_deployment" + }, + "description": "Sample for GetDeployment", + "file": "config_v1_generated_config_get_deployment_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "config_v1_generated_Config_GetDeployment_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": "config_v1_generated_config_get_deployment_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.config_v1.ConfigAsyncClient", + "shortName": "ConfigAsyncClient" + }, + "fullName": "google.cloud.config_v1.ConfigAsyncClient.get_preview", + "method": { + "fullName": "google.cloud.config.v1.Config.GetPreview", + "service": { + "fullName": "google.cloud.config.v1.Config", + "shortName": "Config" + }, + "shortName": "GetPreview" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.config_v1.types.GetPreviewRequest" + }, + { + "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.config_v1.types.Preview", + "shortName": "get_preview" + }, + "description": "Sample for GetPreview", + "file": "config_v1_generated_config_get_preview_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "config_v1_generated_Config_GetPreview_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": "config_v1_generated_config_get_preview_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.config_v1.ConfigClient", + "shortName": "ConfigClient" + }, + "fullName": "google.cloud.config_v1.ConfigClient.get_preview", + "method": { + "fullName": "google.cloud.config.v1.Config.GetPreview", + "service": { + "fullName": "google.cloud.config.v1.Config", + "shortName": "Config" + }, + "shortName": "GetPreview" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.config_v1.types.GetPreviewRequest" + }, + { + "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.config_v1.types.Preview", + "shortName": "get_preview" + }, + "description": "Sample for GetPreview", + "file": "config_v1_generated_config_get_preview_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "config_v1_generated_Config_GetPreview_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": "config_v1_generated_config_get_preview_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.config_v1.ConfigAsyncClient", + "shortName": "ConfigAsyncClient" + }, + "fullName": "google.cloud.config_v1.ConfigAsyncClient.get_resource_change", + "method": { + "fullName": "google.cloud.config.v1.Config.GetResourceChange", + "service": { + "fullName": "google.cloud.config.v1.Config", + "shortName": "Config" + }, + "shortName": "GetResourceChange" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.config_v1.types.GetResourceChangeRequest" + }, + { + "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.config_v1.types.ResourceChange", + "shortName": "get_resource_change" + }, + "description": "Sample for GetResourceChange", + "file": "config_v1_generated_config_get_resource_change_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "config_v1_generated_Config_GetResourceChange_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": "config_v1_generated_config_get_resource_change_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.config_v1.ConfigClient", + "shortName": "ConfigClient" + }, + "fullName": "google.cloud.config_v1.ConfigClient.get_resource_change", + "method": { + "fullName": "google.cloud.config.v1.Config.GetResourceChange", + "service": { + "fullName": "google.cloud.config.v1.Config", + "shortName": "Config" + }, + "shortName": "GetResourceChange" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.config_v1.types.GetResourceChangeRequest" + }, + { + "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.config_v1.types.ResourceChange", + "shortName": "get_resource_change" + }, + "description": "Sample for GetResourceChange", + "file": "config_v1_generated_config_get_resource_change_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "config_v1_generated_Config_GetResourceChange_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": "config_v1_generated_config_get_resource_change_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.config_v1.ConfigAsyncClient", + "shortName": "ConfigAsyncClient" + }, + "fullName": "google.cloud.config_v1.ConfigAsyncClient.get_resource_drift", + "method": { + "fullName": "google.cloud.config.v1.Config.GetResourceDrift", + "service": { + "fullName": "google.cloud.config.v1.Config", + "shortName": "Config" + }, + "shortName": "GetResourceDrift" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.config_v1.types.GetResourceDriftRequest" + }, + { + "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.config_v1.types.ResourceDrift", + "shortName": "get_resource_drift" + }, + "description": "Sample for GetResourceDrift", + "file": "config_v1_generated_config_get_resource_drift_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "config_v1_generated_Config_GetResourceDrift_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": "config_v1_generated_config_get_resource_drift_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.config_v1.ConfigClient", + "shortName": "ConfigClient" + }, + "fullName": "google.cloud.config_v1.ConfigClient.get_resource_drift", + "method": { + "fullName": "google.cloud.config.v1.Config.GetResourceDrift", + "service": { + "fullName": "google.cloud.config.v1.Config", + "shortName": "Config" + }, + "shortName": "GetResourceDrift" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.config_v1.types.GetResourceDriftRequest" + }, + { + "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.config_v1.types.ResourceDrift", + "shortName": "get_resource_drift" + }, + "description": "Sample for GetResourceDrift", + "file": "config_v1_generated_config_get_resource_drift_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "config_v1_generated_Config_GetResourceDrift_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": "config_v1_generated_config_get_resource_drift_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.config_v1.ConfigAsyncClient", + "shortName": "ConfigAsyncClient" + }, + "fullName": "google.cloud.config_v1.ConfigAsyncClient.get_resource", + "method": { + "fullName": "google.cloud.config.v1.Config.GetResource", + "service": { + "fullName": "google.cloud.config.v1.Config", + "shortName": "Config" + }, + "shortName": "GetResource" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.config_v1.types.GetResourceRequest" + }, + { + "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.config_v1.types.Resource", + "shortName": "get_resource" + }, + "description": "Sample for GetResource", + "file": "config_v1_generated_config_get_resource_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "config_v1_generated_Config_GetResource_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": "config_v1_generated_config_get_resource_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.config_v1.ConfigClient", + "shortName": "ConfigClient" + }, + "fullName": "google.cloud.config_v1.ConfigClient.get_resource", + "method": { + "fullName": "google.cloud.config.v1.Config.GetResource", + "service": { + "fullName": "google.cloud.config.v1.Config", + "shortName": "Config" + }, + "shortName": "GetResource" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.config_v1.types.GetResourceRequest" + }, + { + "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.config_v1.types.Resource", + "shortName": "get_resource" + }, + "description": "Sample for GetResource", + "file": "config_v1_generated_config_get_resource_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "config_v1_generated_Config_GetResource_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": "config_v1_generated_config_get_resource_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.config_v1.ConfigAsyncClient", + "shortName": "ConfigAsyncClient" + }, + "fullName": "google.cloud.config_v1.ConfigAsyncClient.get_revision", + "method": { + "fullName": "google.cloud.config.v1.Config.GetRevision", + "service": { + "fullName": "google.cloud.config.v1.Config", + "shortName": "Config" + }, + "shortName": "GetRevision" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.config_v1.types.GetRevisionRequest" + }, + { + "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.config_v1.types.Revision", + "shortName": "get_revision" + }, + "description": "Sample for GetRevision", + "file": "config_v1_generated_config_get_revision_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "config_v1_generated_Config_GetRevision_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": "config_v1_generated_config_get_revision_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.config_v1.ConfigClient", + "shortName": "ConfigClient" + }, + "fullName": "google.cloud.config_v1.ConfigClient.get_revision", + "method": { + "fullName": "google.cloud.config.v1.Config.GetRevision", + "service": { + "fullName": "google.cloud.config.v1.Config", + "shortName": "Config" + }, + "shortName": "GetRevision" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.config_v1.types.GetRevisionRequest" + }, + { + "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.config_v1.types.Revision", + "shortName": "get_revision" + }, + "description": "Sample for GetRevision", + "file": "config_v1_generated_config_get_revision_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "config_v1_generated_Config_GetRevision_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": "config_v1_generated_config_get_revision_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.config_v1.ConfigAsyncClient", + "shortName": "ConfigAsyncClient" + }, + "fullName": "google.cloud.config_v1.ConfigAsyncClient.get_terraform_version", + "method": { + "fullName": "google.cloud.config.v1.Config.GetTerraformVersion", + "service": { + "fullName": "google.cloud.config.v1.Config", + "shortName": "Config" + }, + "shortName": "GetTerraformVersion" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.config_v1.types.GetTerraformVersionRequest" + }, + { + "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.config_v1.types.TerraformVersion", + "shortName": "get_terraform_version" + }, + "description": "Sample for GetTerraformVersion", + "file": "config_v1_generated_config_get_terraform_version_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "config_v1_generated_Config_GetTerraformVersion_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": "config_v1_generated_config_get_terraform_version_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.config_v1.ConfigClient", + "shortName": "ConfigClient" + }, + "fullName": "google.cloud.config_v1.ConfigClient.get_terraform_version", + "method": { + "fullName": "google.cloud.config.v1.Config.GetTerraformVersion", + "service": { + "fullName": "google.cloud.config.v1.Config", + "shortName": "Config" + }, + "shortName": "GetTerraformVersion" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.config_v1.types.GetTerraformVersionRequest" + }, + { + "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.config_v1.types.TerraformVersion", + "shortName": "get_terraform_version" + }, + "description": "Sample for GetTerraformVersion", + "file": "config_v1_generated_config_get_terraform_version_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "config_v1_generated_Config_GetTerraformVersion_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": "config_v1_generated_config_get_terraform_version_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.config_v1.ConfigAsyncClient", + "shortName": "ConfigAsyncClient" + }, + "fullName": "google.cloud.config_v1.ConfigAsyncClient.import_statefile", + "method": { + "fullName": "google.cloud.config.v1.Config.ImportStatefile", + "service": { + "fullName": "google.cloud.config.v1.Config", + "shortName": "Config" + }, + "shortName": "ImportStatefile" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.config_v1.types.ImportStatefileRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "lock_id", + "type": "int" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.config_v1.types.Statefile", + "shortName": "import_statefile" + }, + "description": "Sample for ImportStatefile", + "file": "config_v1_generated_config_import_statefile_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "config_v1_generated_Config_ImportStatefile_async", + "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": "config_v1_generated_config_import_statefile_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.config_v1.ConfigClient", + "shortName": "ConfigClient" + }, + "fullName": "google.cloud.config_v1.ConfigClient.import_statefile", + "method": { + "fullName": "google.cloud.config.v1.Config.ImportStatefile", + "service": { + "fullName": "google.cloud.config.v1.Config", + "shortName": "Config" + }, + "shortName": "ImportStatefile" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.config_v1.types.ImportStatefileRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "lock_id", + "type": "int" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.config_v1.types.Statefile", + "shortName": "import_statefile" + }, + "description": "Sample for ImportStatefile", + "file": "config_v1_generated_config_import_statefile_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "config_v1_generated_Config_ImportStatefile_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": "config_v1_generated_config_import_statefile_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.config_v1.ConfigAsyncClient", + "shortName": "ConfigAsyncClient" + }, + "fullName": "google.cloud.config_v1.ConfigAsyncClient.list_deployments", + "method": { + "fullName": "google.cloud.config.v1.Config.ListDeployments", + "service": { + "fullName": "google.cloud.config.v1.Config", + "shortName": "Config" + }, + "shortName": "ListDeployments" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.config_v1.types.ListDeploymentsRequest" + }, + { + "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.config_v1.services.config.pagers.ListDeploymentsAsyncPager", + "shortName": "list_deployments" + }, + "description": "Sample for ListDeployments", + "file": "config_v1_generated_config_list_deployments_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "config_v1_generated_Config_ListDeployments_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": "config_v1_generated_config_list_deployments_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.config_v1.ConfigClient", + "shortName": "ConfigClient" + }, + "fullName": "google.cloud.config_v1.ConfigClient.list_deployments", + "method": { + "fullName": "google.cloud.config.v1.Config.ListDeployments", + "service": { + "fullName": "google.cloud.config.v1.Config", + "shortName": "Config" + }, + "shortName": "ListDeployments" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.config_v1.types.ListDeploymentsRequest" + }, + { + "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.config_v1.services.config.pagers.ListDeploymentsPager", + "shortName": "list_deployments" + }, + "description": "Sample for ListDeployments", + "file": "config_v1_generated_config_list_deployments_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "config_v1_generated_Config_ListDeployments_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": "config_v1_generated_config_list_deployments_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.config_v1.ConfigAsyncClient", + "shortName": "ConfigAsyncClient" + }, + "fullName": "google.cloud.config_v1.ConfigAsyncClient.list_previews", + "method": { + "fullName": "google.cloud.config.v1.Config.ListPreviews", + "service": { + "fullName": "google.cloud.config.v1.Config", + "shortName": "Config" + }, + "shortName": "ListPreviews" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.config_v1.types.ListPreviewsRequest" + }, + { + "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.config_v1.services.config.pagers.ListPreviewsAsyncPager", + "shortName": "list_previews" + }, + "description": "Sample for ListPreviews", + "file": "config_v1_generated_config_list_previews_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "config_v1_generated_Config_ListPreviews_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": "config_v1_generated_config_list_previews_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.config_v1.ConfigClient", + "shortName": "ConfigClient" + }, + "fullName": "google.cloud.config_v1.ConfigClient.list_previews", + "method": { + "fullName": "google.cloud.config.v1.Config.ListPreviews", + "service": { + "fullName": "google.cloud.config.v1.Config", + "shortName": "Config" + }, + "shortName": "ListPreviews" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.config_v1.types.ListPreviewsRequest" + }, + { + "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.config_v1.services.config.pagers.ListPreviewsPager", + "shortName": "list_previews" + }, + "description": "Sample for ListPreviews", + "file": "config_v1_generated_config_list_previews_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "config_v1_generated_Config_ListPreviews_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": "config_v1_generated_config_list_previews_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.config_v1.ConfigAsyncClient", + "shortName": "ConfigAsyncClient" + }, + "fullName": "google.cloud.config_v1.ConfigAsyncClient.list_resource_changes", + "method": { + "fullName": "google.cloud.config.v1.Config.ListResourceChanges", + "service": { + "fullName": "google.cloud.config.v1.Config", + "shortName": "Config" + }, + "shortName": "ListResourceChanges" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.config_v1.types.ListResourceChangesRequest" + }, + { + "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.config_v1.services.config.pagers.ListResourceChangesAsyncPager", + "shortName": "list_resource_changes" + }, + "description": "Sample for ListResourceChanges", + "file": "config_v1_generated_config_list_resource_changes_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "config_v1_generated_Config_ListResourceChanges_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": "config_v1_generated_config_list_resource_changes_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.config_v1.ConfigClient", + "shortName": "ConfigClient" + }, + "fullName": "google.cloud.config_v1.ConfigClient.list_resource_changes", + "method": { + "fullName": "google.cloud.config.v1.Config.ListResourceChanges", + "service": { + "fullName": "google.cloud.config.v1.Config", + "shortName": "Config" + }, + "shortName": "ListResourceChanges" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.config_v1.types.ListResourceChangesRequest" + }, + { + "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.config_v1.services.config.pagers.ListResourceChangesPager", + "shortName": "list_resource_changes" + }, + "description": "Sample for ListResourceChanges", + "file": "config_v1_generated_config_list_resource_changes_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "config_v1_generated_Config_ListResourceChanges_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": "config_v1_generated_config_list_resource_changes_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.config_v1.ConfigAsyncClient", + "shortName": "ConfigAsyncClient" + }, + "fullName": "google.cloud.config_v1.ConfigAsyncClient.list_resource_drifts", + "method": { + "fullName": "google.cloud.config.v1.Config.ListResourceDrifts", + "service": { + "fullName": "google.cloud.config.v1.Config", + "shortName": "Config" + }, + "shortName": "ListResourceDrifts" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.config_v1.types.ListResourceDriftsRequest" + }, + { + "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.config_v1.services.config.pagers.ListResourceDriftsAsyncPager", + "shortName": "list_resource_drifts" + }, + "description": "Sample for ListResourceDrifts", + "file": "config_v1_generated_config_list_resource_drifts_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "config_v1_generated_Config_ListResourceDrifts_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": "config_v1_generated_config_list_resource_drifts_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.config_v1.ConfigClient", + "shortName": "ConfigClient" + }, + "fullName": "google.cloud.config_v1.ConfigClient.list_resource_drifts", + "method": { + "fullName": "google.cloud.config.v1.Config.ListResourceDrifts", + "service": { + "fullName": "google.cloud.config.v1.Config", + "shortName": "Config" + }, + "shortName": "ListResourceDrifts" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.config_v1.types.ListResourceDriftsRequest" + }, + { + "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.config_v1.services.config.pagers.ListResourceDriftsPager", + "shortName": "list_resource_drifts" + }, + "description": "Sample for ListResourceDrifts", + "file": "config_v1_generated_config_list_resource_drifts_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "config_v1_generated_Config_ListResourceDrifts_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": "config_v1_generated_config_list_resource_drifts_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.config_v1.ConfigAsyncClient", + "shortName": "ConfigAsyncClient" + }, + "fullName": "google.cloud.config_v1.ConfigAsyncClient.list_resources", + "method": { + "fullName": "google.cloud.config.v1.Config.ListResources", + "service": { + "fullName": "google.cloud.config.v1.Config", + "shortName": "Config" + }, + "shortName": "ListResources" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.config_v1.types.ListResourcesRequest" + }, + { + "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.config_v1.services.config.pagers.ListResourcesAsyncPager", + "shortName": "list_resources" + }, + "description": "Sample for ListResources", + "file": "config_v1_generated_config_list_resources_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "config_v1_generated_Config_ListResources_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": "config_v1_generated_config_list_resources_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.config_v1.ConfigClient", + "shortName": "ConfigClient" + }, + "fullName": "google.cloud.config_v1.ConfigClient.list_resources", + "method": { + "fullName": "google.cloud.config.v1.Config.ListResources", + "service": { + "fullName": "google.cloud.config.v1.Config", + "shortName": "Config" + }, + "shortName": "ListResources" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.config_v1.types.ListResourcesRequest" + }, + { + "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.config_v1.services.config.pagers.ListResourcesPager", + "shortName": "list_resources" + }, + "description": "Sample for ListResources", + "file": "config_v1_generated_config_list_resources_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "config_v1_generated_Config_ListResources_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": "config_v1_generated_config_list_resources_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.config_v1.ConfigAsyncClient", + "shortName": "ConfigAsyncClient" + }, + "fullName": "google.cloud.config_v1.ConfigAsyncClient.list_revisions", + "method": { + "fullName": "google.cloud.config.v1.Config.ListRevisions", + "service": { + "fullName": "google.cloud.config.v1.Config", + "shortName": "Config" + }, + "shortName": "ListRevisions" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.config_v1.types.ListRevisionsRequest" + }, + { + "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.config_v1.services.config.pagers.ListRevisionsAsyncPager", + "shortName": "list_revisions" + }, + "description": "Sample for ListRevisions", + "file": "config_v1_generated_config_list_revisions_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "config_v1_generated_Config_ListRevisions_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": "config_v1_generated_config_list_revisions_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.config_v1.ConfigClient", + "shortName": "ConfigClient" + }, + "fullName": "google.cloud.config_v1.ConfigClient.list_revisions", + "method": { + "fullName": "google.cloud.config.v1.Config.ListRevisions", + "service": { + "fullName": "google.cloud.config.v1.Config", + "shortName": "Config" + }, + "shortName": "ListRevisions" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.config_v1.types.ListRevisionsRequest" + }, + { + "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.config_v1.services.config.pagers.ListRevisionsPager", + "shortName": "list_revisions" + }, + "description": "Sample for ListRevisions", + "file": "config_v1_generated_config_list_revisions_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "config_v1_generated_Config_ListRevisions_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": "config_v1_generated_config_list_revisions_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.config_v1.ConfigAsyncClient", + "shortName": "ConfigAsyncClient" + }, + "fullName": "google.cloud.config_v1.ConfigAsyncClient.list_terraform_versions", + "method": { + "fullName": "google.cloud.config.v1.Config.ListTerraformVersions", + "service": { + "fullName": "google.cloud.config.v1.Config", + "shortName": "Config" + }, + "shortName": "ListTerraformVersions" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.config_v1.types.ListTerraformVersionsRequest" + }, + { + "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.config_v1.services.config.pagers.ListTerraformVersionsAsyncPager", + "shortName": "list_terraform_versions" + }, + "description": "Sample for ListTerraformVersions", + "file": "config_v1_generated_config_list_terraform_versions_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "config_v1_generated_Config_ListTerraformVersions_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": "config_v1_generated_config_list_terraform_versions_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.config_v1.ConfigClient", + "shortName": "ConfigClient" + }, + "fullName": "google.cloud.config_v1.ConfigClient.list_terraform_versions", + "method": { + "fullName": "google.cloud.config.v1.Config.ListTerraformVersions", + "service": { + "fullName": "google.cloud.config.v1.Config", + "shortName": "Config" + }, + "shortName": "ListTerraformVersions" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.config_v1.types.ListTerraformVersionsRequest" + }, + { + "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.config_v1.services.config.pagers.ListTerraformVersionsPager", + "shortName": "list_terraform_versions" + }, + "description": "Sample for ListTerraformVersions", + "file": "config_v1_generated_config_list_terraform_versions_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "config_v1_generated_Config_ListTerraformVersions_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": "config_v1_generated_config_list_terraform_versions_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.config_v1.ConfigAsyncClient", + "shortName": "ConfigAsyncClient" + }, + "fullName": "google.cloud.config_v1.ConfigAsyncClient.lock_deployment", + "method": { + "fullName": "google.cloud.config.v1.Config.LockDeployment", + "service": { + "fullName": "google.cloud.config.v1.Config", + "shortName": "Config" + }, + "shortName": "LockDeployment" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.config_v1.types.LockDeploymentRequest" + }, + { + "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": "lock_deployment" + }, + "description": "Sample for LockDeployment", + "file": "config_v1_generated_config_lock_deployment_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "config_v1_generated_Config_LockDeployment_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": "config_v1_generated_config_lock_deployment_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.config_v1.ConfigClient", + "shortName": "ConfigClient" + }, + "fullName": "google.cloud.config_v1.ConfigClient.lock_deployment", + "method": { + "fullName": "google.cloud.config.v1.Config.LockDeployment", + "service": { + "fullName": "google.cloud.config.v1.Config", + "shortName": "Config" + }, + "shortName": "LockDeployment" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.config_v1.types.LockDeploymentRequest" + }, + { + "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": "lock_deployment" + }, + "description": "Sample for LockDeployment", + "file": "config_v1_generated_config_lock_deployment_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "config_v1_generated_Config_LockDeployment_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": "config_v1_generated_config_lock_deployment_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.config_v1.ConfigAsyncClient", + "shortName": "ConfigAsyncClient" + }, + "fullName": "google.cloud.config_v1.ConfigAsyncClient.unlock_deployment", + "method": { + "fullName": "google.cloud.config.v1.Config.UnlockDeployment", + "service": { + "fullName": "google.cloud.config.v1.Config", + "shortName": "Config" + }, + "shortName": "UnlockDeployment" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.config_v1.types.UnlockDeploymentRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "lock_id", + "type": "int" + }, + { + "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": "unlock_deployment" + }, + "description": "Sample for UnlockDeployment", + "file": "config_v1_generated_config_unlock_deployment_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "config_v1_generated_Config_UnlockDeployment_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": "config_v1_generated_config_unlock_deployment_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.config_v1.ConfigClient", + "shortName": "ConfigClient" + }, + "fullName": "google.cloud.config_v1.ConfigClient.unlock_deployment", + "method": { + "fullName": "google.cloud.config.v1.Config.UnlockDeployment", + "service": { + "fullName": "google.cloud.config.v1.Config", + "shortName": "Config" + }, + "shortName": "UnlockDeployment" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.config_v1.types.UnlockDeploymentRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "lock_id", + "type": "int" + }, + { + "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": "unlock_deployment" + }, + "description": "Sample for UnlockDeployment", + "file": "config_v1_generated_config_unlock_deployment_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "config_v1_generated_Config_UnlockDeployment_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": "config_v1_generated_config_unlock_deployment_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.config_v1.ConfigAsyncClient", + "shortName": "ConfigAsyncClient" + }, + "fullName": "google.cloud.config_v1.ConfigAsyncClient.update_deployment", + "method": { + "fullName": "google.cloud.config.v1.Config.UpdateDeployment", + "service": { + "fullName": "google.cloud.config.v1.Config", + "shortName": "Config" + }, + "shortName": "UpdateDeployment" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.config_v1.types.UpdateDeploymentRequest" + }, + { + "name": "deployment", + "type": "google.cloud.config_v1.types.Deployment" + }, + { + "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_deployment" + }, + "description": "Sample for UpdateDeployment", + "file": "config_v1_generated_config_update_deployment_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "config_v1_generated_Config_UpdateDeployment_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": "config_v1_generated_config_update_deployment_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.config_v1.ConfigClient", + "shortName": "ConfigClient" + }, + "fullName": "google.cloud.config_v1.ConfigClient.update_deployment", + "method": { + "fullName": "google.cloud.config.v1.Config.UpdateDeployment", + "service": { + "fullName": "google.cloud.config.v1.Config", + "shortName": "Config" + }, + "shortName": "UpdateDeployment" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.config_v1.types.UpdateDeploymentRequest" + }, + { + "name": "deployment", + "type": "google.cloud.config_v1.types.Deployment" + }, + { + "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_deployment" + }, + "description": "Sample for UpdateDeployment", + "file": "config_v1_generated_config_update_deployment_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "config_v1_generated_Config_UpdateDeployment_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": "config_v1_generated_config_update_deployment_sync.py" + } + ] +} diff --git a/owl-bot-staging/google-cloud-config/v1/scripts/fixup_config_v1_keywords.py b/owl-bot-staging/google-cloud-config/v1/scripts/fixup_config_v1_keywords.py new file mode 100644 index 000000000000..c3a279472125 --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/scripts/fixup_config_v1_keywords.py @@ -0,0 +1,202 @@ +#! /usr/bin/env python3 +# -*- 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. +# +import argparse +import os +import libcst as cst +import pathlib +import sys +from typing import (Any, Callable, Dict, List, Sequence, Tuple) + + +def partition( + predicate: Callable[[Any], bool], + iterator: Sequence[Any] +) -> Tuple[List[Any], List[Any]]: + """A stable, out-of-place partition.""" + results = ([], []) + + for i in iterator: + results[int(predicate(i))].append(i) + + # Returns trueList, falseList + return results[1], results[0] + + +class configCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'create_deployment': ('parent', 'deployment_id', 'deployment', 'request_id', ), + 'create_preview': ('parent', 'preview', 'preview_id', 'request_id', ), + 'delete_deployment': ('name', 'request_id', 'force', 'delete_policy', ), + 'delete_preview': ('name', 'request_id', ), + 'delete_statefile': ('name', 'lock_id', ), + 'export_deployment_statefile': ('parent', 'draft', ), + 'export_lock_info': ('name', ), + 'export_preview_result': ('parent', ), + 'export_revision_statefile': ('parent', ), + 'get_deployment': ('name', ), + 'get_preview': ('name', ), + 'get_resource': ('name', ), + 'get_resource_change': ('name', ), + 'get_resource_drift': ('name', ), + 'get_revision': ('name', ), + 'get_terraform_version': ('name', ), + 'import_statefile': ('parent', 'lock_id', 'skip_draft', ), + 'list_deployments': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), + 'list_previews': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), + 'list_resource_changes': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), + 'list_resource_drifts': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), + 'list_resources': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), + 'list_revisions': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), + 'list_terraform_versions': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), + 'lock_deployment': ('name', ), + 'unlock_deployment': ('name', 'lock_id', ), + 'update_deployment': ('deployment', 'update_mask', 'request_id', ), + } + + def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: + try: + key = original.func.attr.value + kword_params = self.METHOD_TO_PARAMS[key] + except (AttributeError, KeyError): + # Either not a method from the API or too convoluted to be sure. + return updated + + # If the existing code is valid, keyword args come after positional args. + # Therefore, all positional args must map to the first parameters. + args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) + if any(k.keyword.value == "request" for k in kwargs): + # We've already fixed this file, don't fix it again. + return updated + + kwargs, ctrl_kwargs = partition( + lambda a: a.keyword.value not in self.CTRL_PARAMS, + kwargs + ) + + args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] + ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) + for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) + + request_arg = cst.Arg( + value=cst.Dict([ + cst.DictElement( + cst.SimpleString("'{}'".format(name)), +cst.Element(value=arg.value) + ) + # Note: the args + kwargs looks silly, but keep in mind that + # the control parameters had to be stripped out, and that + # those could have been passed positionally or by keyword. + for name, arg in zip(kword_params, args + kwargs)]), + keyword=cst.Name("request") + ) + + return updated.with_changes( + args=[request_arg] + ctrl_kwargs + ) + + +def fix_files( + in_dir: pathlib.Path, + out_dir: pathlib.Path, + *, + transformer=configCallTransformer(), +): + """Duplicate the input dir to the output dir, fixing file method calls. + + Preconditions: + * in_dir is a real directory + * out_dir is a real, empty directory + """ + pyfile_gen = ( + pathlib.Path(os.path.join(root, f)) + for root, _, files in os.walk(in_dir) + for f in files if os.path.splitext(f)[1] == ".py" + ) + + for fpath in pyfile_gen: + with open(fpath, 'r') as f: + src = f.read() + + # Parse the code and insert method call fixes. + tree = cst.parse_module(src) + updated = tree.visit(transformer) + + # Create the path and directory structure for the new file. + updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) + updated_path.parent.mkdir(parents=True, exist_ok=True) + + # Generate the updated source file at the corresponding path. + with open(updated_path, 'w') as f: + f.write(updated.code) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description="""Fix up source that uses the config client library. + +The existing sources are NOT overwritten but are copied to output_dir with changes made. + +Note: This tool operates at a best-effort level at converting positional + parameters in client method calls to keyword based parameters. + Cases where it WILL FAIL include + A) * or ** expansion in a method call. + B) Calls via function or method alias (includes free function calls) + C) Indirect or dispatched calls (e.g. the method is looked up dynamically) + + These all constitute false negatives. The tool will also detect false + positives when an API method shares a name with another method. +""") + parser.add_argument( + '-d', + '--input-directory', + required=True, + dest='input_dir', + help='the input directory to walk for python files to fix up', + ) + parser.add_argument( + '-o', + '--output-directory', + required=True, + dest='output_dir', + help='the directory to output files fixed via un-flattening', + ) + args = parser.parse_args() + input_dir = pathlib.Path(args.input_dir) + output_dir = pathlib.Path(args.output_dir) + if not input_dir.is_dir(): + print( + f"input directory '{input_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if not output_dir.is_dir(): + print( + f"output directory '{output_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if os.listdir(output_dir): + print( + f"output directory '{output_dir}' is not empty", + file=sys.stderr, + ) + sys.exit(-1) + + fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/google-cloud-config/v1/setup.py b/owl-bot-staging/google-cloud-config/v1/setup.py new file mode 100644 index 000000000000..07c589a6f969 --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/setup.py @@ -0,0 +1,99 @@ +# -*- 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. +# +import io +import os +import re + +import setuptools # type: ignore + +package_root = os.path.abspath(os.path.dirname(__file__)) + +name = 'google-cloud-config' + + +description = "Google Cloud Config API client library" + +version = None + +with open(os.path.join(package_root, 'google/cloud/config/gapic_version.py')) as fp: + version_candidates = re.findall(r"(?<=\")\d+.\d+.\d+(?=\")", fp.read()) + assert (len(version_candidates) == 1) + version = version_candidates[0] + +if version[0] == "0": + release_status = "Development Status :: 4 - Beta" +else: + release_status = "Development Status :: 5 - Production/Stable" + +dependencies = [ + "google-api-core[grpc] >= 1.34.1, <3.0.0,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0,!=2.24.0,!=2.25.0", + "proto-plus >= 1.22.3, <2.0.0", + "proto-plus >= 1.25.0, <2.0.0; python_version >= '3.13'", + "protobuf>=3.20.2,<7.0.0,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", + "grpc-google-iam-v1 >= 0.14.0, <1.0.0", +] +extras = { +} +url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-config" + +package_root = os.path.abspath(os.path.dirname(__file__)) + +readme_filename = os.path.join(package_root, "README.rst") +with io.open(readme_filename, encoding="utf-8") as readme_file: + readme = readme_file.read() + +packages = [ + package + for package in setuptools.find_namespace_packages() + if package.startswith("google") +] + +setuptools.setup( + name=name, + version=version, + description=description, + long_description=readme, + author="Google LLC", + author_email="googleapis-packages@google.com", + license="Apache 2.0", + url=url, + classifiers=[ + release_status, + "Intended Audience :: Developers", + "License :: OSI Approved :: Apache Software License", + "Programming Language :: Python", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", + "Operating System :: OS Independent", + "Topic :: Internet", + ], + platforms="Posix; MacOS X; Windows", + packages=packages, + python_requires=">=3.7", + install_requires=dependencies, + extras_require=extras, + include_package_data=True, + zip_safe=False, +) diff --git a/owl-bot-staging/google-cloud-config/v1/testing/constraints-3.10.txt b/owl-bot-staging/google-cloud-config/v1/testing/constraints-3.10.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/testing/constraints-3.10.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-config/v1/testing/constraints-3.11.txt b/owl-bot-staging/google-cloud-config/v1/testing/constraints-3.11.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/testing/constraints-3.11.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-config/v1/testing/constraints-3.12.txt b/owl-bot-staging/google-cloud-config/v1/testing/constraints-3.12.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/testing/constraints-3.12.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-config/v1/testing/constraints-3.13.txt b/owl-bot-staging/google-cloud-config/v1/testing/constraints-3.13.txt new file mode 100644 index 000000000000..2010e549cceb --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/testing/constraints-3.13.txt @@ -0,0 +1,12 @@ +# We use the constraints file for the latest Python version +# (currently this file) to check that the latest +# major versions of dependencies are supported in setup.py. +# List all library dependencies and extras in this file. +# Require the latest major version be installed for each dependency. +# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0", +# Then this file should have google-cloud-foo>=1 +google-api-core>=2 +google-auth>=2 +proto-plus>=1 +protobuf>=6 +grpc-google-iam-v1>=0 diff --git a/owl-bot-staging/google-cloud-config/v1/testing/constraints-3.7.txt b/owl-bot-staging/google-cloud-config/v1/testing/constraints-3.7.txt new file mode 100644 index 000000000000..56affbd9bd75 --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/testing/constraints-3.7.txt @@ -0,0 +1,11 @@ +# This constraints file is used to check that lower bounds +# are correct in setup.py +# List all library dependencies and extras in this file. +# Pin the version to the lower bound. +# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0", +# Then this file should have google-cloud-foo==1.14.0 +google-api-core==1.34.1 +google-auth==2.14.1 +proto-plus==1.22.3 +protobuf==3.20.2 +grpc-google-iam-v1==0.14.0 diff --git a/owl-bot-staging/google-cloud-config/v1/testing/constraints-3.8.txt b/owl-bot-staging/google-cloud-config/v1/testing/constraints-3.8.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/testing/constraints-3.8.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-config/v1/testing/constraints-3.9.txt b/owl-bot-staging/google-cloud-config/v1/testing/constraints-3.9.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/testing/constraints-3.9.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-config/v1/tests/__init__.py b/owl-bot-staging/google-cloud-config/v1/tests/__init__.py new file mode 100644 index 000000000000..191773d5572d --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- 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. +# diff --git a/owl-bot-staging/google-cloud-config/v1/tests/unit/__init__.py b/owl-bot-staging/google-cloud-config/v1/tests/unit/__init__.py new file mode 100644 index 000000000000..191773d5572d --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- 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. +# diff --git a/owl-bot-staging/google-cloud-config/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/google-cloud-config/v1/tests/unit/gapic/__init__.py new file mode 100644 index 000000000000..191773d5572d --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- 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. +# diff --git a/owl-bot-staging/google-cloud-config/v1/tests/unit/gapic/config_v1/__init__.py b/owl-bot-staging/google-cloud-config/v1/tests/unit/gapic/config_v1/__init__.py new file mode 100644 index 000000000000..191773d5572d --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/tests/unit/gapic/config_v1/__init__.py @@ -0,0 +1,16 @@ + +# -*- 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. +# diff --git a/owl-bot-staging/google-cloud-config/v1/tests/unit/gapic/config_v1/test_config.py b/owl-bot-staging/google-cloud-config/v1/tests/unit/gapic/config_v1/test_config.py new file mode 100644 index 000000000000..6beae688408a --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/tests/unit/gapic/config_v1/test_config.py @@ -0,0 +1,23350 @@ +# -*- 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. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable, AsyncIterable +from google.protobuf import json_format +import json +import math +import pytest +from google.api_core import api_core_version +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +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 + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template +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.config_v1.services.config import ConfigAsyncClient +from google.cloud.config_v1.services.config import ConfigClient +from google.cloud.config_v1.services.config import pagers +from google.cloud.config_v1.services.config import transports +from google.cloud.config_v1.types import config +from google.cloud.location import locations_pb2 +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import options_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account +from google.protobuf import any_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +import google.auth + + + +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) + + +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 + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert ConfigClient._get_default_mtls_endpoint(None) is None + assert ConfigClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert ConfigClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert ConfigClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert ConfigClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert ConfigClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert ConfigClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert ConfigClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert ConfigClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + ConfigClient._read_environment_variables() + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert ConfigClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert ConfigClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert ConfigClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + ConfigClient._read_environment_variables() + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + + with mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"}): + assert ConfigClient._read_environment_variables() == (False, "auto", "foo.com") + +def test__get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert ConfigClient._get_client_cert_source(None, False) is None + assert ConfigClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert ConfigClient._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 ConfigClient._get_client_cert_source(None, True) is mock_default_cert_source + assert ConfigClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(ConfigClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ConfigClient)) +@mock.patch.object(ConfigAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ConfigAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = ConfigClient._DEFAULT_UNIVERSE + default_endpoint = ConfigClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = ConfigClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert ConfigClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert ConfigClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == ConfigClient.DEFAULT_MTLS_ENDPOINT + assert ConfigClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert ConfigClient._get_api_endpoint(None, None, default_universe, "always") == ConfigClient.DEFAULT_MTLS_ENDPOINT + assert ConfigClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == ConfigClient.DEFAULT_MTLS_ENDPOINT + assert ConfigClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert ConfigClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + ConfigClient._get_api_endpoint(None, mock_client_cert_source, mock_universe, "auto") + assert str(excinfo.value) == "mTLS is not supported in any universe other than googleapis.com." + + +def test__get_universe_domain(): + client_universe_domain = "foo.com" + universe_domain_env = "bar.com" + + assert ConfigClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert ConfigClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert ConfigClient._get_universe_domain(None, None) == ConfigClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + ConfigClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + +@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 = ConfigClient(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 = ConfigClient(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", [ + (ConfigClient, "grpc"), + (ConfigAsyncClient, "grpc_asyncio"), + (ConfigClient, "rest"), +]) +def test_config_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 == ( + 'config.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://config.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.ConfigGrpcTransport, "grpc"), + (transports.ConfigGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.ConfigRestTransport, "rest"), +]) +def test_config_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", [ + (ConfigClient, "grpc"), + (ConfigAsyncClient, "grpc_asyncio"), + (ConfigClient, "rest"), +]) +def test_config_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 == ( + 'config.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://config.googleapis.com' + ) + + +def test_config_client_get_transport_class(): + transport = ConfigClient.get_transport_class() + available_transports = [ + transports.ConfigGrpcTransport, + transports.ConfigRestTransport, + ] + assert transport in available_transports + + transport = ConfigClient.get_transport_class("grpc") + assert transport == transports.ConfigGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ConfigClient, transports.ConfigGrpcTransport, "grpc"), + (ConfigAsyncClient, transports.ConfigGrpcAsyncIOTransport, "grpc_asyncio"), + (ConfigClient, transports.ConfigRestTransport, "rest"), +]) +@mock.patch.object(ConfigClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ConfigClient)) +@mock.patch.object(ConfigAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ConfigAsyncClient)) +def test_config_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(ConfigClient, '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(ConfigClient, '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 GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + client = client_class(transport=transport_name) + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + + # 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", [ + (ConfigClient, transports.ConfigGrpcTransport, "grpc", "true"), + (ConfigAsyncClient, transports.ConfigGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (ConfigClient, transports.ConfigGrpcTransport, "grpc", "false"), + (ConfigAsyncClient, transports.ConfigGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (ConfigClient, transports.ConfigRestTransport, "rest", "true"), + (ConfigClient, transports.ConfigRestTransport, "rest", "false"), +]) +@mock.patch.object(ConfigClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ConfigClient)) +@mock.patch.object(ConfigAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ConfigAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_config_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", [ + ConfigClient, ConfigAsyncClient +]) +@mock.patch.object(ConfigClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConfigClient)) +@mock.patch.object(ConfigAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConfigAsyncClient)) +def test_config_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_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`" + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + +@pytest.mark.parametrize("client_class", [ + ConfigClient, ConfigAsyncClient +]) +@mock.patch.object(ConfigClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ConfigClient)) +@mock.patch.object(ConfigAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ConfigAsyncClient)) +def test_config_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = ConfigClient._DEFAULT_UNIVERSE + default_endpoint = ConfigClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = ConfigClient._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", [ + (ConfigClient, transports.ConfigGrpcTransport, "grpc"), + (ConfigAsyncClient, transports.ConfigGrpcAsyncIOTransport, "grpc_asyncio"), + (ConfigClient, transports.ConfigRestTransport, "rest"), +]) +def test_config_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", [ + (ConfigClient, transports.ConfigGrpcTransport, "grpc", grpc_helpers), + (ConfigAsyncClient, transports.ConfigGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (ConfigClient, transports.ConfigRestTransport, "rest", None), +]) +def test_config_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_config_client_client_options_from_dict(): + with mock.patch('google.cloud.config_v1.services.config.transports.ConfigGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = ConfigClient( + 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", [ + (ConfigClient, transports.ConfigGrpcTransport, "grpc", grpc_helpers), + (ConfigAsyncClient, transports.ConfigGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_config_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( + "config.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="config.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + config.ListDeploymentsRequest, + dict, +]) +def test_list_deployments(request_type, transport: str = 'grpc'): + client = ConfigClient( + 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_deployments), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = config.ListDeploymentsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + response = client.list_deployments(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = config.ListDeploymentsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDeploymentsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_deployments_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 = ConfigClient( + 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 = config.ListDeploymentsRequest( + 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_deployments), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_deployments(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == config.ListDeploymentsRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + order_by='order_by_value', + ) + +def test_list_deployments_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create 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 = ConfigClient( + 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_deployments in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_deployments] = mock_rpc + request = {} + client.list_deployments(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_deployments(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_deployments_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 = ConfigAsyncClient( + 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_deployments 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_deployments] = mock_rpc + + request = {} + await client.list_deployments(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_deployments(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_deployments_async(transport: str = 'grpc_asyncio', request_type=config.ListDeploymentsRequest): + client = ConfigAsyncClient( + 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_deployments), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(config.ListDeploymentsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_deployments(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = config.ListDeploymentsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDeploymentsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.asyncio +async def test_list_deployments_async_from_dict(): + await test_list_deployments_async(request_type=dict) + +def test_list_deployments_field_headers(): + client = ConfigClient( + 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 = config.ListDeploymentsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_deployments), + '__call__') as call: + call.return_value = config.ListDeploymentsResponse() + client.list_deployments(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_deployments_field_headers_async(): + client = ConfigAsyncClient( + 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 = config.ListDeploymentsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_deployments), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.ListDeploymentsResponse()) + await client.list_deployments(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_deployments_flattened(): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_deployments), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = config.ListDeploymentsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_deployments( + 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_deployments_flattened_error(): + client = ConfigClient( + 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_deployments( + config.ListDeploymentsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_deployments_flattened_async(): + client = ConfigAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_deployments), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = config.ListDeploymentsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.ListDeploymentsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_deployments( + 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_deployments_flattened_error_async(): + client = ConfigAsyncClient( + 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_deployments( + config.ListDeploymentsRequest(), + parent='parent_value', + ) + + +def test_list_deployments_pager(transport_name: str = "grpc"): + client = ConfigClient( + 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_deployments), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + config.ListDeploymentsResponse( + deployments=[ + config.Deployment(), + config.Deployment(), + config.Deployment(), + ], + next_page_token='abc', + ), + config.ListDeploymentsResponse( + deployments=[], + next_page_token='def', + ), + config.ListDeploymentsResponse( + deployments=[ + config.Deployment(), + ], + next_page_token='ghi', + ), + config.ListDeploymentsResponse( + deployments=[ + config.Deployment(), + config.Deployment(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_deployments(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, config.Deployment) + for i in results) +def test_list_deployments_pages(transport_name: str = "grpc"): + client = ConfigClient( + 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_deployments), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + config.ListDeploymentsResponse( + deployments=[ + config.Deployment(), + config.Deployment(), + config.Deployment(), + ], + next_page_token='abc', + ), + config.ListDeploymentsResponse( + deployments=[], + next_page_token='def', + ), + config.ListDeploymentsResponse( + deployments=[ + config.Deployment(), + ], + next_page_token='ghi', + ), + config.ListDeploymentsResponse( + deployments=[ + config.Deployment(), + config.Deployment(), + ], + ), + RuntimeError, + ) + pages = list(client.list_deployments(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_deployments_async_pager(): + client = ConfigAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_deployments), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + config.ListDeploymentsResponse( + deployments=[ + config.Deployment(), + config.Deployment(), + config.Deployment(), + ], + next_page_token='abc', + ), + config.ListDeploymentsResponse( + deployments=[], + next_page_token='def', + ), + config.ListDeploymentsResponse( + deployments=[ + config.Deployment(), + ], + next_page_token='ghi', + ), + config.ListDeploymentsResponse( + deployments=[ + config.Deployment(), + config.Deployment(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_deployments(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, config.Deployment) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_deployments_async_pages(): + client = ConfigAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_deployments), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + config.ListDeploymentsResponse( + deployments=[ + config.Deployment(), + config.Deployment(), + config.Deployment(), + ], + next_page_token='abc', + ), + config.ListDeploymentsResponse( + deployments=[], + next_page_token='def', + ), + config.ListDeploymentsResponse( + deployments=[ + config.Deployment(), + ], + next_page_token='ghi', + ), + config.ListDeploymentsResponse( + deployments=[ + config.Deployment(), + config.Deployment(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_deployments(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", [ + config.GetDeploymentRequest, + dict, +]) +def test_get_deployment(request_type, transport: str = 'grpc'): + client = ConfigClient( + 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_deployment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = config.Deployment( + name='name_value', + state=config.Deployment.State.CREATING, + latest_revision='latest_revision_value', + state_detail='state_detail_value', + error_code=config.Deployment.ErrorCode.REVISION_FAILED, + delete_build='delete_build_value', + delete_logs='delete_logs_value', + error_logs='error_logs_value', + artifacts_gcs_bucket='artifacts_gcs_bucket_value', + service_account='service_account_value', + import_existing_resources=True, + worker_pool='worker_pool_value', + lock_state=config.Deployment.LockState.LOCKED, + tf_version_constraint='tf_version_constraint_value', + tf_version='tf_version_value', + quota_validation=config.QuotaValidation.ENABLED, + ) + response = client.get_deployment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = config.GetDeploymentRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, config.Deployment) + assert response.name == 'name_value' + assert response.state == config.Deployment.State.CREATING + assert response.latest_revision == 'latest_revision_value' + assert response.state_detail == 'state_detail_value' + assert response.error_code == config.Deployment.ErrorCode.REVISION_FAILED + assert response.delete_build == 'delete_build_value' + assert response.delete_logs == 'delete_logs_value' + assert response.error_logs == 'error_logs_value' + assert response.artifacts_gcs_bucket == 'artifacts_gcs_bucket_value' + assert response.service_account == 'service_account_value' + assert response.import_existing_resources is True + assert response.worker_pool == 'worker_pool_value' + assert response.lock_state == config.Deployment.LockState.LOCKED + assert response.tf_version_constraint == 'tf_version_constraint_value' + assert response.tf_version == 'tf_version_value' + assert response.quota_validation == config.QuotaValidation.ENABLED + + +def test_get_deployment_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 = ConfigClient( + 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 = config.GetDeploymentRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_deployment), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_deployment(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == config.GetDeploymentRequest( + name='name_value', + ) + +def test_get_deployment_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create 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 = ConfigClient( + 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_deployment in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_deployment] = mock_rpc + request = {} + client.get_deployment(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_deployment(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_deployment_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 = ConfigAsyncClient( + 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_deployment 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_deployment] = mock_rpc + + request = {} + await client.get_deployment(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_deployment(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_deployment_async(transport: str = 'grpc_asyncio', request_type=config.GetDeploymentRequest): + client = ConfigAsyncClient( + 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_deployment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(config.Deployment( + name='name_value', + state=config.Deployment.State.CREATING, + latest_revision='latest_revision_value', + state_detail='state_detail_value', + error_code=config.Deployment.ErrorCode.REVISION_FAILED, + delete_build='delete_build_value', + delete_logs='delete_logs_value', + error_logs='error_logs_value', + artifacts_gcs_bucket='artifacts_gcs_bucket_value', + service_account='service_account_value', + import_existing_resources=True, + worker_pool='worker_pool_value', + lock_state=config.Deployment.LockState.LOCKED, + tf_version_constraint='tf_version_constraint_value', + tf_version='tf_version_value', + quota_validation=config.QuotaValidation.ENABLED, + )) + response = await client.get_deployment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = config.GetDeploymentRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, config.Deployment) + assert response.name == 'name_value' + assert response.state == config.Deployment.State.CREATING + assert response.latest_revision == 'latest_revision_value' + assert response.state_detail == 'state_detail_value' + assert response.error_code == config.Deployment.ErrorCode.REVISION_FAILED + assert response.delete_build == 'delete_build_value' + assert response.delete_logs == 'delete_logs_value' + assert response.error_logs == 'error_logs_value' + assert response.artifacts_gcs_bucket == 'artifacts_gcs_bucket_value' + assert response.service_account == 'service_account_value' + assert response.import_existing_resources is True + assert response.worker_pool == 'worker_pool_value' + assert response.lock_state == config.Deployment.LockState.LOCKED + assert response.tf_version_constraint == 'tf_version_constraint_value' + assert response.tf_version == 'tf_version_value' + assert response.quota_validation == config.QuotaValidation.ENABLED + + +@pytest.mark.asyncio +async def test_get_deployment_async_from_dict(): + await test_get_deployment_async(request_type=dict) + +def test_get_deployment_field_headers(): + client = ConfigClient( + 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 = config.GetDeploymentRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_deployment), + '__call__') as call: + call.return_value = config.Deployment() + client.get_deployment(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_deployment_field_headers_async(): + client = ConfigAsyncClient( + 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 = config.GetDeploymentRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_deployment), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.Deployment()) + await client.get_deployment(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_deployment_flattened(): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_deployment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = config.Deployment() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_deployment( + 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_deployment_flattened_error(): + client = ConfigClient( + 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_deployment( + config.GetDeploymentRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_deployment_flattened_async(): + client = ConfigAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_deployment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = config.Deployment() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.Deployment()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_deployment( + 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_deployment_flattened_error_async(): + client = ConfigAsyncClient( + 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_deployment( + config.GetDeploymentRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + config.CreateDeploymentRequest, + dict, +]) +def test_create_deployment(request_type, transport: str = 'grpc'): + client = ConfigClient( + 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_deployment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_deployment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = config.CreateDeploymentRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_deployment_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 = ConfigClient( + 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 = config.CreateDeploymentRequest( + parent='parent_value', + deployment_id='deployment_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_deployment), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_deployment(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == config.CreateDeploymentRequest( + parent='parent_value', + deployment_id='deployment_id_value', + request_id='request_id_value', + ) + +def test_create_deployment_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create 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 = ConfigClient( + 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_deployment in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_deployment] = mock_rpc + request = {} + client.create_deployment(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_deployment(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_deployment_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 = ConfigAsyncClient( + 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_deployment 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_deployment] = mock_rpc + + request = {} + await client.create_deployment(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_deployment(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_deployment_async(transport: str = 'grpc_asyncio', request_type=config.CreateDeploymentRequest): + client = ConfigAsyncClient( + 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_deployment), + '__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_deployment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = config.CreateDeploymentRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_deployment_async_from_dict(): + await test_create_deployment_async(request_type=dict) + +def test_create_deployment_field_headers(): + client = ConfigClient( + 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 = config.CreateDeploymentRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_deployment), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_deployment(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_deployment_field_headers_async(): + client = ConfigAsyncClient( + 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 = config.CreateDeploymentRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_deployment), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_deployment(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_deployment_flattened(): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_deployment), + '__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_deployment( + parent='parent_value', + deployment=config.Deployment(terraform_blueprint=config.TerraformBlueprint(gcs_source='gcs_source_value')), + deployment_id='deployment_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].deployment + mock_val = config.Deployment(terraform_blueprint=config.TerraformBlueprint(gcs_source='gcs_source_value')) + assert arg == mock_val + arg = args[0].deployment_id + mock_val = 'deployment_id_value' + assert arg == mock_val + + +def test_create_deployment_flattened_error(): + client = ConfigClient( + 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_deployment( + config.CreateDeploymentRequest(), + parent='parent_value', + deployment=config.Deployment(terraform_blueprint=config.TerraformBlueprint(gcs_source='gcs_source_value')), + deployment_id='deployment_id_value', + ) + +@pytest.mark.asyncio +async def test_create_deployment_flattened_async(): + client = ConfigAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_deployment), + '__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_deployment( + parent='parent_value', + deployment=config.Deployment(terraform_blueprint=config.TerraformBlueprint(gcs_source='gcs_source_value')), + deployment_id='deployment_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].deployment + mock_val = config.Deployment(terraform_blueprint=config.TerraformBlueprint(gcs_source='gcs_source_value')) + assert arg == mock_val + arg = args[0].deployment_id + mock_val = 'deployment_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_deployment_flattened_error_async(): + client = ConfigAsyncClient( + 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_deployment( + config.CreateDeploymentRequest(), + parent='parent_value', + deployment=config.Deployment(terraform_blueprint=config.TerraformBlueprint(gcs_source='gcs_source_value')), + deployment_id='deployment_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + config.UpdateDeploymentRequest, + dict, +]) +def test_update_deployment(request_type, transport: str = 'grpc'): + client = ConfigClient( + 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_deployment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.update_deployment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = config.UpdateDeploymentRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_deployment_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 = ConfigClient( + 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 = config.UpdateDeploymentRequest( + request_id='request_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_deployment), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_deployment(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == config.UpdateDeploymentRequest( + request_id='request_id_value', + ) + +def test_update_deployment_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create 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 = ConfigClient( + 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_deployment in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_deployment] = mock_rpc + request = {} + client.update_deployment(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_deployment(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_deployment_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 = ConfigAsyncClient( + 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_deployment 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_deployment] = mock_rpc + + request = {} + await client.update_deployment(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_deployment(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_deployment_async(transport: str = 'grpc_asyncio', request_type=config.UpdateDeploymentRequest): + client = ConfigAsyncClient( + 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_deployment), + '__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_deployment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = config.UpdateDeploymentRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_update_deployment_async_from_dict(): + await test_update_deployment_async(request_type=dict) + +def test_update_deployment_field_headers(): + client = ConfigClient( + 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 = config.UpdateDeploymentRequest() + + request.deployment.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_deployment), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_deployment(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', + 'deployment.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_deployment_field_headers_async(): + client = ConfigAsyncClient( + 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 = config.UpdateDeploymentRequest() + + request.deployment.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_deployment), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.update_deployment(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', + 'deployment.name=name_value', + ) in kw['metadata'] + + +def test_update_deployment_flattened(): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_deployment), + '__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_deployment( + deployment=config.Deployment(terraform_blueprint=config.TerraformBlueprint(gcs_source='gcs_source_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].deployment + mock_val = config.Deployment(terraform_blueprint=config.TerraformBlueprint(gcs_source='gcs_source_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_deployment_flattened_error(): + client = ConfigClient( + 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_deployment( + config.UpdateDeploymentRequest(), + deployment=config.Deployment(terraform_blueprint=config.TerraformBlueprint(gcs_source='gcs_source_value')), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_deployment_flattened_async(): + client = ConfigAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_deployment), + '__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_deployment( + deployment=config.Deployment(terraform_blueprint=config.TerraformBlueprint(gcs_source='gcs_source_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].deployment + mock_val = config.Deployment(terraform_blueprint=config.TerraformBlueprint(gcs_source='gcs_source_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_deployment_flattened_error_async(): + client = ConfigAsyncClient( + 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_deployment( + config.UpdateDeploymentRequest(), + deployment=config.Deployment(terraform_blueprint=config.TerraformBlueprint(gcs_source='gcs_source_value')), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + config.DeleteDeploymentRequest, + dict, +]) +def test_delete_deployment(request_type, transport: str = 'grpc'): + client = ConfigClient( + 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_deployment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_deployment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = config.DeleteDeploymentRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_deployment_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 = ConfigClient( + 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 = config.DeleteDeploymentRequest( + 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_deployment), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_deployment(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == config.DeleteDeploymentRequest( + name='name_value', + request_id='request_id_value', + ) + +def test_delete_deployment_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create 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 = ConfigClient( + 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_deployment in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_deployment] = mock_rpc + request = {} + client.delete_deployment(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_deployment(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_deployment_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 = ConfigAsyncClient( + 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_deployment 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_deployment] = mock_rpc + + request = {} + await client.delete_deployment(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_deployment(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_deployment_async(transport: str = 'grpc_asyncio', request_type=config.DeleteDeploymentRequest): + client = ConfigAsyncClient( + 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_deployment), + '__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_deployment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = config.DeleteDeploymentRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_deployment_async_from_dict(): + await test_delete_deployment_async(request_type=dict) + +def test_delete_deployment_field_headers(): + client = ConfigClient( + 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 = config.DeleteDeploymentRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_deployment), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_deployment(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_deployment_field_headers_async(): + client = ConfigAsyncClient( + 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 = config.DeleteDeploymentRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_deployment), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_deployment(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_deployment_flattened(): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_deployment), + '__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_deployment( + 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_deployment_flattened_error(): + client = ConfigClient( + 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_deployment( + config.DeleteDeploymentRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_deployment_flattened_async(): + client = ConfigAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_deployment), + '__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_deployment( + 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_deployment_flattened_error_async(): + client = ConfigAsyncClient( + 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_deployment( + config.DeleteDeploymentRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + config.ListRevisionsRequest, + dict, +]) +def test_list_revisions(request_type, transport: str = 'grpc'): + client = ConfigClient( + 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_revisions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = config.ListRevisionsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + response = client.list_revisions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = config.ListRevisionsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListRevisionsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_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 = ConfigClient( + 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 = config.ListRevisionsRequest( + 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_revisions), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_revisions(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == config.ListRevisionsRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + order_by='order_by_value', + ) + +def test_list_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 = ConfigClient( + 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_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_revisions] = mock_rpc + request = {} + client.list_revisions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_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_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 = ConfigAsyncClient( + 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_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_revisions] = mock_rpc + + request = {} + await client.list_revisions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_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_revisions_async(transport: str = 'grpc_asyncio', request_type=config.ListRevisionsRequest): + client = ConfigAsyncClient( + 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_revisions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(config.ListRevisionsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_revisions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = config.ListRevisionsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListRevisionsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.asyncio +async def test_list_revisions_async_from_dict(): + await test_list_revisions_async(request_type=dict) + +def test_list_revisions_field_headers(): + client = ConfigClient( + 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 = config.ListRevisionsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_revisions), + '__call__') as call: + call.return_value = config.ListRevisionsResponse() + client.list_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_revisions_field_headers_async(): + client = ConfigAsyncClient( + 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 = config.ListRevisionsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_revisions), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.ListRevisionsResponse()) + await client.list_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_revisions_flattened(): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_revisions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = config.ListRevisionsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_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_revisions_flattened_error(): + client = ConfigClient( + 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_revisions( + config.ListRevisionsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_revisions_flattened_async(): + client = ConfigAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_revisions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = config.ListRevisionsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.ListRevisionsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_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_revisions_flattened_error_async(): + client = ConfigAsyncClient( + 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_revisions( + config.ListRevisionsRequest(), + parent='parent_value', + ) + + +def test_list_revisions_pager(transport_name: str = "grpc"): + client = ConfigClient( + 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_revisions), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + config.ListRevisionsResponse( + revisions=[ + config.Revision(), + config.Revision(), + config.Revision(), + ], + next_page_token='abc', + ), + config.ListRevisionsResponse( + revisions=[], + next_page_token='def', + ), + config.ListRevisionsResponse( + revisions=[ + config.Revision(), + ], + next_page_token='ghi', + ), + config.ListRevisionsResponse( + revisions=[ + config.Revision(), + config.Revision(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_revisions(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, config.Revision) + for i in results) +def test_list_revisions_pages(transport_name: str = "grpc"): + client = ConfigClient( + 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_revisions), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + config.ListRevisionsResponse( + revisions=[ + config.Revision(), + config.Revision(), + config.Revision(), + ], + next_page_token='abc', + ), + config.ListRevisionsResponse( + revisions=[], + next_page_token='def', + ), + config.ListRevisionsResponse( + revisions=[ + config.Revision(), + ], + next_page_token='ghi', + ), + config.ListRevisionsResponse( + revisions=[ + config.Revision(), + config.Revision(), + ], + ), + RuntimeError, + ) + pages = list(client.list_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_revisions_async_pager(): + client = ConfigAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_revisions), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + config.ListRevisionsResponse( + revisions=[ + config.Revision(), + config.Revision(), + config.Revision(), + ], + next_page_token='abc', + ), + config.ListRevisionsResponse( + revisions=[], + next_page_token='def', + ), + config.ListRevisionsResponse( + revisions=[ + config.Revision(), + ], + next_page_token='ghi', + ), + config.ListRevisionsResponse( + revisions=[ + config.Revision(), + config.Revision(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_revisions(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, config.Revision) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_revisions_async_pages(): + client = ConfigAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_revisions), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + config.ListRevisionsResponse( + revisions=[ + config.Revision(), + config.Revision(), + config.Revision(), + ], + next_page_token='abc', + ), + config.ListRevisionsResponse( + revisions=[], + next_page_token='def', + ), + config.ListRevisionsResponse( + revisions=[ + config.Revision(), + ], + next_page_token='ghi', + ), + config.ListRevisionsResponse( + revisions=[ + config.Revision(), + config.Revision(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_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", [ + config.GetRevisionRequest, + dict, +]) +def test_get_revision(request_type, transport: str = 'grpc'): + client = ConfigClient( + 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_revision), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = config.Revision( + name='name_value', + action=config.Revision.Action.CREATE, + state=config.Revision.State.APPLYING, + state_detail='state_detail_value', + error_code=config.Revision.ErrorCode.CLOUD_BUILD_PERMISSION_DENIED, + build='build_value', + logs='logs_value', + error_logs='error_logs_value', + service_account='service_account_value', + import_existing_resources=True, + worker_pool='worker_pool_value', + tf_version_constraint='tf_version_constraint_value', + tf_version='tf_version_value', + quota_validation_results='quota_validation_results_value', + quota_validation=config.QuotaValidation.ENABLED, + ) + response = client.get_revision(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = config.GetRevisionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, config.Revision) + assert response.name == 'name_value' + assert response.action == config.Revision.Action.CREATE + assert response.state == config.Revision.State.APPLYING + assert response.state_detail == 'state_detail_value' + assert response.error_code == config.Revision.ErrorCode.CLOUD_BUILD_PERMISSION_DENIED + assert response.build == 'build_value' + assert response.logs == 'logs_value' + assert response.error_logs == 'error_logs_value' + assert response.service_account == 'service_account_value' + assert response.import_existing_resources is True + assert response.worker_pool == 'worker_pool_value' + assert response.tf_version_constraint == 'tf_version_constraint_value' + assert response.tf_version == 'tf_version_value' + assert response.quota_validation_results == 'quota_validation_results_value' + assert response.quota_validation == config.QuotaValidation.ENABLED + + +def test_get_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 = ConfigClient( + 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 = config.GetRevisionRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_revision), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_revision(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == config.GetRevisionRequest( + name='name_value', + ) + +def test_get_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 = ConfigClient( + 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_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_revision] = mock_rpc + request = {} + client.get_revision(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_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_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 = ConfigAsyncClient( + 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_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_revision] = mock_rpc + + request = {} + await client.get_revision(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_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_revision_async(transport: str = 'grpc_asyncio', request_type=config.GetRevisionRequest): + client = ConfigAsyncClient( + 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_revision), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(config.Revision( + name='name_value', + action=config.Revision.Action.CREATE, + state=config.Revision.State.APPLYING, + state_detail='state_detail_value', + error_code=config.Revision.ErrorCode.CLOUD_BUILD_PERMISSION_DENIED, + build='build_value', + logs='logs_value', + error_logs='error_logs_value', + service_account='service_account_value', + import_existing_resources=True, + worker_pool='worker_pool_value', + tf_version_constraint='tf_version_constraint_value', + tf_version='tf_version_value', + quota_validation_results='quota_validation_results_value', + quota_validation=config.QuotaValidation.ENABLED, + )) + response = await client.get_revision(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = config.GetRevisionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, config.Revision) + assert response.name == 'name_value' + assert response.action == config.Revision.Action.CREATE + assert response.state == config.Revision.State.APPLYING + assert response.state_detail == 'state_detail_value' + assert response.error_code == config.Revision.ErrorCode.CLOUD_BUILD_PERMISSION_DENIED + assert response.build == 'build_value' + assert response.logs == 'logs_value' + assert response.error_logs == 'error_logs_value' + assert response.service_account == 'service_account_value' + assert response.import_existing_resources is True + assert response.worker_pool == 'worker_pool_value' + assert response.tf_version_constraint == 'tf_version_constraint_value' + assert response.tf_version == 'tf_version_value' + assert response.quota_validation_results == 'quota_validation_results_value' + assert response.quota_validation == config.QuotaValidation.ENABLED + + +@pytest.mark.asyncio +async def test_get_revision_async_from_dict(): + await test_get_revision_async(request_type=dict) + +def test_get_revision_field_headers(): + client = ConfigClient( + 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 = config.GetRevisionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_revision), + '__call__') as call: + call.return_value = config.Revision() + client.get_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_revision_field_headers_async(): + client = ConfigAsyncClient( + 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 = config.GetRevisionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_revision), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.Revision()) + await client.get_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_revision_flattened(): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_revision), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = config.Revision() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_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_revision_flattened_error(): + client = ConfigClient( + 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_revision( + config.GetRevisionRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_revision_flattened_async(): + client = ConfigAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_revision), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = config.Revision() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.Revision()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_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_revision_flattened_error_async(): + client = ConfigAsyncClient( + 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_revision( + config.GetRevisionRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + config.GetResourceRequest, + dict, +]) +def test_get_resource(request_type, transport: str = 'grpc'): + client = ConfigClient( + 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_resource), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = config.Resource( + name='name_value', + intent=config.Resource.Intent.CREATE, + state=config.Resource.State.PLANNED, + ) + response = client.get_resource(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = config.GetResourceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, config.Resource) + assert response.name == 'name_value' + assert response.intent == config.Resource.Intent.CREATE + assert response.state == config.Resource.State.PLANNED + + +def test_get_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 = ConfigClient( + 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 = config.GetResourceRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_resource), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_resource(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == config.GetResourceRequest( + name='name_value', + ) + +def test_get_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 = ConfigClient( + 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_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_resource] = mock_rpc + request = {} + client.get_resource(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_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_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 = ConfigAsyncClient( + 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_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_resource] = mock_rpc + + request = {} + await client.get_resource(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_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_resource_async(transport: str = 'grpc_asyncio', request_type=config.GetResourceRequest): + client = ConfigAsyncClient( + 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_resource), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(config.Resource( + name='name_value', + intent=config.Resource.Intent.CREATE, + state=config.Resource.State.PLANNED, + )) + response = await client.get_resource(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = config.GetResourceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, config.Resource) + assert response.name == 'name_value' + assert response.intent == config.Resource.Intent.CREATE + assert response.state == config.Resource.State.PLANNED + + +@pytest.mark.asyncio +async def test_get_resource_async_from_dict(): + await test_get_resource_async(request_type=dict) + +def test_get_resource_field_headers(): + client = ConfigClient( + 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 = config.GetResourceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_resource), + '__call__') as call: + call.return_value = config.Resource() + client.get_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_resource_field_headers_async(): + client = ConfigAsyncClient( + 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 = config.GetResourceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_resource), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.Resource()) + await client.get_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_resource_flattened(): + client = ConfigClient( + 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), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = config.Resource() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_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_resource_flattened_error(): + client = ConfigClient( + 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_resource( + config.GetResourceRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_resource_flattened_async(): + client = ConfigAsyncClient( + 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), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = config.Resource() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.Resource()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_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_resource_flattened_error_async(): + client = ConfigAsyncClient( + 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_resource( + config.GetResourceRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + config.ListResourcesRequest, + dict, +]) +def test_list_resources(request_type, transport: str = 'grpc'): + client = ConfigClient( + 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_resources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = config.ListResourcesResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + response = client.list_resources(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = config.ListResourcesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListResourcesPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_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 = ConfigClient( + 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 = config.ListResourcesRequest( + 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_resources), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_resources(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == config.ListResourcesRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + order_by='order_by_value', + ) + +def test_list_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 = ConfigClient( + 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_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_resources] = mock_rpc + request = {} + client.list_resources(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_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_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 = ConfigAsyncClient( + 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_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_resources] = mock_rpc + + request = {} + await client.list_resources(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_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_resources_async(transport: str = 'grpc_asyncio', request_type=config.ListResourcesRequest): + client = ConfigAsyncClient( + 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_resources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(config.ListResourcesResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_resources(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = config.ListResourcesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListResourcesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.asyncio +async def test_list_resources_async_from_dict(): + await test_list_resources_async(request_type=dict) + +def test_list_resources_field_headers(): + client = ConfigClient( + 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 = config.ListResourcesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_resources), + '__call__') as call: + call.return_value = config.ListResourcesResponse() + client.list_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_resources_field_headers_async(): + client = ConfigAsyncClient( + 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 = config.ListResourcesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_resources), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.ListResourcesResponse()) + await client.list_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_resources_flattened(): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_resources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = config.ListResourcesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_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_resources_flattened_error(): + client = ConfigClient( + 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_resources( + config.ListResourcesRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_resources_flattened_async(): + client = ConfigAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_resources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = config.ListResourcesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.ListResourcesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_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_resources_flattened_error_async(): + client = ConfigAsyncClient( + 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_resources( + config.ListResourcesRequest(), + parent='parent_value', + ) + + +def test_list_resources_pager(transport_name: str = "grpc"): + client = ConfigClient( + 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_resources), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + config.ListResourcesResponse( + resources=[ + config.Resource(), + config.Resource(), + config.Resource(), + ], + next_page_token='abc', + ), + config.ListResourcesResponse( + resources=[], + next_page_token='def', + ), + config.ListResourcesResponse( + resources=[ + config.Resource(), + ], + next_page_token='ghi', + ), + config.ListResourcesResponse( + resources=[ + config.Resource(), + config.Resource(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_resources(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, config.Resource) + for i in results) +def test_list_resources_pages(transport_name: str = "grpc"): + client = ConfigClient( + 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_resources), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + config.ListResourcesResponse( + resources=[ + config.Resource(), + config.Resource(), + config.Resource(), + ], + next_page_token='abc', + ), + config.ListResourcesResponse( + resources=[], + next_page_token='def', + ), + config.ListResourcesResponse( + resources=[ + config.Resource(), + ], + next_page_token='ghi', + ), + config.ListResourcesResponse( + resources=[ + config.Resource(), + config.Resource(), + ], + ), + RuntimeError, + ) + pages = list(client.list_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_resources_async_pager(): + client = ConfigAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_resources), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + config.ListResourcesResponse( + resources=[ + config.Resource(), + config.Resource(), + config.Resource(), + ], + next_page_token='abc', + ), + config.ListResourcesResponse( + resources=[], + next_page_token='def', + ), + config.ListResourcesResponse( + resources=[ + config.Resource(), + ], + next_page_token='ghi', + ), + config.ListResourcesResponse( + resources=[ + config.Resource(), + config.Resource(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_resources(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, config.Resource) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_resources_async_pages(): + client = ConfigAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_resources), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + config.ListResourcesResponse( + resources=[ + config.Resource(), + config.Resource(), + config.Resource(), + ], + next_page_token='abc', + ), + config.ListResourcesResponse( + resources=[], + next_page_token='def', + ), + config.ListResourcesResponse( + resources=[ + config.Resource(), + ], + next_page_token='ghi', + ), + config.ListResourcesResponse( + resources=[ + config.Resource(), + config.Resource(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_resources(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", [ + config.ExportDeploymentStatefileRequest, + dict, +]) +def test_export_deployment_statefile(request_type, transport: str = 'grpc'): + client = ConfigClient( + 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.export_deployment_statefile), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = config.Statefile( + signed_uri='signed_uri_value', + ) + response = client.export_deployment_statefile(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = config.ExportDeploymentStatefileRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, config.Statefile) + assert response.signed_uri == 'signed_uri_value' + + +def test_export_deployment_statefile_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 = ConfigClient( + 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 = config.ExportDeploymentStatefileRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.export_deployment_statefile), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.export_deployment_statefile(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == config.ExportDeploymentStatefileRequest( + parent='parent_value', + ) + +def test_export_deployment_statefile_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create 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 = ConfigClient( + 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.export_deployment_statefile in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.export_deployment_statefile] = mock_rpc + request = {} + client.export_deployment_statefile(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.export_deployment_statefile(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_export_deployment_statefile_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 = ConfigAsyncClient( + 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.export_deployment_statefile 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.export_deployment_statefile] = mock_rpc + + request = {} + await client.export_deployment_statefile(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.export_deployment_statefile(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_export_deployment_statefile_async(transport: str = 'grpc_asyncio', request_type=config.ExportDeploymentStatefileRequest): + client = ConfigAsyncClient( + 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.export_deployment_statefile), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(config.Statefile( + signed_uri='signed_uri_value', + )) + response = await client.export_deployment_statefile(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = config.ExportDeploymentStatefileRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, config.Statefile) + assert response.signed_uri == 'signed_uri_value' + + +@pytest.mark.asyncio +async def test_export_deployment_statefile_async_from_dict(): + await test_export_deployment_statefile_async(request_type=dict) + +def test_export_deployment_statefile_field_headers(): + client = ConfigClient( + 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 = config.ExportDeploymentStatefileRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.export_deployment_statefile), + '__call__') as call: + call.return_value = config.Statefile() + client.export_deployment_statefile(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_export_deployment_statefile_field_headers_async(): + client = ConfigAsyncClient( + 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 = config.ExportDeploymentStatefileRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.export_deployment_statefile), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.Statefile()) + await client.export_deployment_statefile(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'] + + +@pytest.mark.parametrize("request_type", [ + config.ExportRevisionStatefileRequest, + dict, +]) +def test_export_revision_statefile(request_type, transport: str = 'grpc'): + client = ConfigClient( + 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.export_revision_statefile), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = config.Statefile( + signed_uri='signed_uri_value', + ) + response = client.export_revision_statefile(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = config.ExportRevisionStatefileRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, config.Statefile) + assert response.signed_uri == 'signed_uri_value' + + +def test_export_revision_statefile_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 = ConfigClient( + 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 = config.ExportRevisionStatefileRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.export_revision_statefile), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.export_revision_statefile(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == config.ExportRevisionStatefileRequest( + parent='parent_value', + ) + +def test_export_revision_statefile_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create 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 = ConfigClient( + 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.export_revision_statefile in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.export_revision_statefile] = mock_rpc + request = {} + client.export_revision_statefile(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.export_revision_statefile(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_export_revision_statefile_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 = ConfigAsyncClient( + 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.export_revision_statefile 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.export_revision_statefile] = mock_rpc + + request = {} + await client.export_revision_statefile(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.export_revision_statefile(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_export_revision_statefile_async(transport: str = 'grpc_asyncio', request_type=config.ExportRevisionStatefileRequest): + client = ConfigAsyncClient( + 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.export_revision_statefile), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(config.Statefile( + signed_uri='signed_uri_value', + )) + response = await client.export_revision_statefile(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = config.ExportRevisionStatefileRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, config.Statefile) + assert response.signed_uri == 'signed_uri_value' + + +@pytest.mark.asyncio +async def test_export_revision_statefile_async_from_dict(): + await test_export_revision_statefile_async(request_type=dict) + +def test_export_revision_statefile_field_headers(): + client = ConfigClient( + 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 = config.ExportRevisionStatefileRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.export_revision_statefile), + '__call__') as call: + call.return_value = config.Statefile() + client.export_revision_statefile(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_export_revision_statefile_field_headers_async(): + client = ConfigAsyncClient( + 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 = config.ExportRevisionStatefileRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.export_revision_statefile), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.Statefile()) + await client.export_revision_statefile(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'] + + +@pytest.mark.parametrize("request_type", [ + config.ImportStatefileRequest, + dict, +]) +def test_import_statefile(request_type, transport: str = 'grpc'): + client = ConfigClient( + 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.import_statefile), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = config.Statefile( + signed_uri='signed_uri_value', + ) + response = client.import_statefile(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = config.ImportStatefileRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, config.Statefile) + assert response.signed_uri == 'signed_uri_value' + + +def test_import_statefile_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 = ConfigClient( + 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 = config.ImportStatefileRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_statefile), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.import_statefile(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == config.ImportStatefileRequest( + parent='parent_value', + ) + +def test_import_statefile_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create 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 = ConfigClient( + 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.import_statefile in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.import_statefile] = mock_rpc + request = {} + client.import_statefile(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.import_statefile(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_import_statefile_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 = ConfigAsyncClient( + 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.import_statefile 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.import_statefile] = mock_rpc + + request = {} + await client.import_statefile(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.import_statefile(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_import_statefile_async(transport: str = 'grpc_asyncio', request_type=config.ImportStatefileRequest): + client = ConfigAsyncClient( + 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.import_statefile), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(config.Statefile( + signed_uri='signed_uri_value', + )) + response = await client.import_statefile(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = config.ImportStatefileRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, config.Statefile) + assert response.signed_uri == 'signed_uri_value' + + +@pytest.mark.asyncio +async def test_import_statefile_async_from_dict(): + await test_import_statefile_async(request_type=dict) + +def test_import_statefile_field_headers(): + client = ConfigClient( + 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 = config.ImportStatefileRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_statefile), + '__call__') as call: + call.return_value = config.Statefile() + client.import_statefile(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_import_statefile_field_headers_async(): + client = ConfigAsyncClient( + 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 = config.ImportStatefileRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_statefile), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.Statefile()) + await client.import_statefile(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_import_statefile_flattened(): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_statefile), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = config.Statefile() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.import_statefile( + parent='parent_value', + lock_id=725, + ) + + # 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].lock_id + mock_val = 725 + assert arg == mock_val + + +def test_import_statefile_flattened_error(): + client = ConfigClient( + 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.import_statefile( + config.ImportStatefileRequest(), + parent='parent_value', + lock_id=725, + ) + +@pytest.mark.asyncio +async def test_import_statefile_flattened_async(): + client = ConfigAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_statefile), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = config.Statefile() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.Statefile()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.import_statefile( + parent='parent_value', + lock_id=725, + ) + + # 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].lock_id + mock_val = 725 + assert arg == mock_val + +@pytest.mark.asyncio +async def test_import_statefile_flattened_error_async(): + client = ConfigAsyncClient( + 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.import_statefile( + config.ImportStatefileRequest(), + parent='parent_value', + lock_id=725, + ) + + +@pytest.mark.parametrize("request_type", [ + config.DeleteStatefileRequest, + dict, +]) +def test_delete_statefile(request_type, transport: str = 'grpc'): + client = ConfigClient( + 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_statefile), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_statefile(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = config.DeleteStatefileRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_statefile_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 = ConfigClient( + 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 = config.DeleteStatefileRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_statefile), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_statefile(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == config.DeleteStatefileRequest( + name='name_value', + ) + +def test_delete_statefile_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create 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 = ConfigClient( + 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_statefile in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_statefile] = mock_rpc + request = {} + client.delete_statefile(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_statefile(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_statefile_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 = ConfigAsyncClient( + 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_statefile 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_statefile] = mock_rpc + + request = {} + await client.delete_statefile(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.delete_statefile(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_statefile_async(transport: str = 'grpc_asyncio', request_type=config.DeleteStatefileRequest): + client = ConfigAsyncClient( + 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_statefile), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_statefile(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = config.DeleteStatefileRequest() + 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_statefile_async_from_dict(): + await test_delete_statefile_async(request_type=dict) + +def test_delete_statefile_field_headers(): + client = ConfigClient( + 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 = config.DeleteStatefileRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_statefile), + '__call__') as call: + call.return_value = None + client.delete_statefile(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_statefile_field_headers_async(): + client = ConfigAsyncClient( + 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 = config.DeleteStatefileRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_statefile), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_statefile(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_statefile_flattened(): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_statefile), + '__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_statefile( + 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_statefile_flattened_error(): + client = ConfigClient( + 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_statefile( + config.DeleteStatefileRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_statefile_flattened_async(): + client = ConfigAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_statefile), + '__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_statefile( + 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_statefile_flattened_error_async(): + client = ConfigAsyncClient( + 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_statefile( + config.DeleteStatefileRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + config.LockDeploymentRequest, + dict, +]) +def test_lock_deployment(request_type, transport: str = 'grpc'): + client = ConfigClient( + 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.lock_deployment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.lock_deployment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = config.LockDeploymentRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_lock_deployment_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 = ConfigClient( + 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 = config.LockDeploymentRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.lock_deployment), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.lock_deployment(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == config.LockDeploymentRequest( + name='name_value', + ) + +def test_lock_deployment_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create 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 = ConfigClient( + 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.lock_deployment in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.lock_deployment] = mock_rpc + request = {} + client.lock_deployment(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.lock_deployment(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_lock_deployment_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 = ConfigAsyncClient( + 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.lock_deployment 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.lock_deployment] = mock_rpc + + request = {} + await client.lock_deployment(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.lock_deployment(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_lock_deployment_async(transport: str = 'grpc_asyncio', request_type=config.LockDeploymentRequest): + client = ConfigAsyncClient( + 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.lock_deployment), + '__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.lock_deployment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = config.LockDeploymentRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_lock_deployment_async_from_dict(): + await test_lock_deployment_async(request_type=dict) + +def test_lock_deployment_field_headers(): + client = ConfigClient( + 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 = config.LockDeploymentRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.lock_deployment), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.lock_deployment(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_lock_deployment_field_headers_async(): + client = ConfigAsyncClient( + 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 = config.LockDeploymentRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.lock_deployment), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.lock_deployment(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_lock_deployment_flattened(): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.lock_deployment), + '__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.lock_deployment( + 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_lock_deployment_flattened_error(): + client = ConfigClient( + 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.lock_deployment( + config.LockDeploymentRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_lock_deployment_flattened_async(): + client = ConfigAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.lock_deployment), + '__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.lock_deployment( + 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_lock_deployment_flattened_error_async(): + client = ConfigAsyncClient( + 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.lock_deployment( + config.LockDeploymentRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + config.UnlockDeploymentRequest, + dict, +]) +def test_unlock_deployment(request_type, transport: str = 'grpc'): + client = ConfigClient( + 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.unlock_deployment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.unlock_deployment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = config.UnlockDeploymentRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_unlock_deployment_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 = ConfigClient( + 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 = config.UnlockDeploymentRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.unlock_deployment), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.unlock_deployment(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == config.UnlockDeploymentRequest( + name='name_value', + ) + +def test_unlock_deployment_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create 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 = ConfigClient( + 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.unlock_deployment in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.unlock_deployment] = mock_rpc + request = {} + client.unlock_deployment(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.unlock_deployment(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_unlock_deployment_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 = ConfigAsyncClient( + 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.unlock_deployment 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.unlock_deployment] = mock_rpc + + request = {} + await client.unlock_deployment(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.unlock_deployment(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_unlock_deployment_async(transport: str = 'grpc_asyncio', request_type=config.UnlockDeploymentRequest): + client = ConfigAsyncClient( + 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.unlock_deployment), + '__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.unlock_deployment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = config.UnlockDeploymentRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_unlock_deployment_async_from_dict(): + await test_unlock_deployment_async(request_type=dict) + +def test_unlock_deployment_field_headers(): + client = ConfigClient( + 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 = config.UnlockDeploymentRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.unlock_deployment), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.unlock_deployment(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_unlock_deployment_field_headers_async(): + client = ConfigAsyncClient( + 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 = config.UnlockDeploymentRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.unlock_deployment), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.unlock_deployment(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_unlock_deployment_flattened(): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.unlock_deployment), + '__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.unlock_deployment( + name='name_value', + lock_id=725, + ) + + # 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].lock_id + mock_val = 725 + assert arg == mock_val + + +def test_unlock_deployment_flattened_error(): + client = ConfigClient( + 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.unlock_deployment( + config.UnlockDeploymentRequest(), + name='name_value', + lock_id=725, + ) + +@pytest.mark.asyncio +async def test_unlock_deployment_flattened_async(): + client = ConfigAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.unlock_deployment), + '__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.unlock_deployment( + name='name_value', + lock_id=725, + ) + + # 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].lock_id + mock_val = 725 + assert arg == mock_val + +@pytest.mark.asyncio +async def test_unlock_deployment_flattened_error_async(): + client = ConfigAsyncClient( + 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.unlock_deployment( + config.UnlockDeploymentRequest(), + name='name_value', + lock_id=725, + ) + + +@pytest.mark.parametrize("request_type", [ + config.ExportLockInfoRequest, + dict, +]) +def test_export_lock_info(request_type, transport: str = 'grpc'): + client = ConfigClient( + 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.export_lock_info), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = config.LockInfo( + lock_id=725, + operation='operation_value', + info='info_value', + who='who_value', + version='version_value', + ) + response = client.export_lock_info(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = config.ExportLockInfoRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, config.LockInfo) + assert response.lock_id == 725 + assert response.operation == 'operation_value' + assert response.info == 'info_value' + assert response.who == 'who_value' + assert response.version == 'version_value' + + +def test_export_lock_info_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 = ConfigClient( + 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 = config.ExportLockInfoRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.export_lock_info), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.export_lock_info(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == config.ExportLockInfoRequest( + name='name_value', + ) + +def test_export_lock_info_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create 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 = ConfigClient( + 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.export_lock_info in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.export_lock_info] = mock_rpc + request = {} + client.export_lock_info(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.export_lock_info(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_export_lock_info_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 = ConfigAsyncClient( + 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.export_lock_info 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.export_lock_info] = mock_rpc + + request = {} + await client.export_lock_info(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.export_lock_info(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_export_lock_info_async(transport: str = 'grpc_asyncio', request_type=config.ExportLockInfoRequest): + client = ConfigAsyncClient( + 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.export_lock_info), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(config.LockInfo( + lock_id=725, + operation='operation_value', + info='info_value', + who='who_value', + version='version_value', + )) + response = await client.export_lock_info(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = config.ExportLockInfoRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, config.LockInfo) + assert response.lock_id == 725 + assert response.operation == 'operation_value' + assert response.info == 'info_value' + assert response.who == 'who_value' + assert response.version == 'version_value' + + +@pytest.mark.asyncio +async def test_export_lock_info_async_from_dict(): + await test_export_lock_info_async(request_type=dict) + +def test_export_lock_info_field_headers(): + client = ConfigClient( + 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 = config.ExportLockInfoRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.export_lock_info), + '__call__') as call: + call.return_value = config.LockInfo() + client.export_lock_info(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_export_lock_info_field_headers_async(): + client = ConfigAsyncClient( + 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 = config.ExportLockInfoRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.export_lock_info), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.LockInfo()) + await client.export_lock_info(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_export_lock_info_flattened(): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.export_lock_info), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = config.LockInfo() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.export_lock_info( + 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_export_lock_info_flattened_error(): + client = ConfigClient( + 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.export_lock_info( + config.ExportLockInfoRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_export_lock_info_flattened_async(): + client = ConfigAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.export_lock_info), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = config.LockInfo() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.LockInfo()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.export_lock_info( + 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_export_lock_info_flattened_error_async(): + client = ConfigAsyncClient( + 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.export_lock_info( + config.ExportLockInfoRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + config.CreatePreviewRequest, + dict, +]) +def test_create_preview(request_type, transport: str = 'grpc'): + client = ConfigClient( + 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_preview), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_preview(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = config.CreatePreviewRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_preview_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 = ConfigClient( + 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 = config.CreatePreviewRequest( + parent='parent_value', + preview_id='preview_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_preview), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_preview(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == config.CreatePreviewRequest( + parent='parent_value', + preview_id='preview_id_value', + ) + +def test_create_preview_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create 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 = ConfigClient( + 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_preview in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_preview] = mock_rpc + request = {} + client.create_preview(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_preview(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_preview_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 = ConfigAsyncClient( + 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_preview 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_preview] = mock_rpc + + request = {} + await client.create_preview(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_preview(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_preview_async(transport: str = 'grpc_asyncio', request_type=config.CreatePreviewRequest): + client = ConfigAsyncClient( + 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_preview), + '__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_preview(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = config.CreatePreviewRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_preview_async_from_dict(): + await test_create_preview_async(request_type=dict) + +def test_create_preview_field_headers(): + client = ConfigClient( + 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 = config.CreatePreviewRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_preview), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_preview(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_preview_field_headers_async(): + client = ConfigAsyncClient( + 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 = config.CreatePreviewRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_preview), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_preview(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_preview_flattened(): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_preview), + '__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_preview( + parent='parent_value', + preview=config.Preview(terraform_blueprint=config.TerraformBlueprint(gcs_source='gcs_source_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].preview + mock_val = config.Preview(terraform_blueprint=config.TerraformBlueprint(gcs_source='gcs_source_value')) + assert arg == mock_val + + +def test_create_preview_flattened_error(): + client = ConfigClient( + 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_preview( + config.CreatePreviewRequest(), + parent='parent_value', + preview=config.Preview(terraform_blueprint=config.TerraformBlueprint(gcs_source='gcs_source_value')), + ) + +@pytest.mark.asyncio +async def test_create_preview_flattened_async(): + client = ConfigAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_preview), + '__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_preview( + parent='parent_value', + preview=config.Preview(terraform_blueprint=config.TerraformBlueprint(gcs_source='gcs_source_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].preview + mock_val = config.Preview(terraform_blueprint=config.TerraformBlueprint(gcs_source='gcs_source_value')) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_preview_flattened_error_async(): + client = ConfigAsyncClient( + 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_preview( + config.CreatePreviewRequest(), + parent='parent_value', + preview=config.Preview(terraform_blueprint=config.TerraformBlueprint(gcs_source='gcs_source_value')), + ) + + +@pytest.mark.parametrize("request_type", [ + config.GetPreviewRequest, + dict, +]) +def test_get_preview(request_type, transport: str = 'grpc'): + client = ConfigClient( + 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_preview), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = config.Preview( + name='name_value', + state=config.Preview.State.CREATING, + deployment='deployment_value', + preview_mode=config.Preview.PreviewMode.DEFAULT, + service_account='service_account_value', + artifacts_gcs_bucket='artifacts_gcs_bucket_value', + worker_pool='worker_pool_value', + error_code=config.Preview.ErrorCode.CLOUD_BUILD_PERMISSION_DENIED, + build='build_value', + error_logs='error_logs_value', + logs='logs_value', + tf_version='tf_version_value', + tf_version_constraint='tf_version_constraint_value', + ) + response = client.get_preview(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = config.GetPreviewRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, config.Preview) + assert response.name == 'name_value' + assert response.state == config.Preview.State.CREATING + assert response.deployment == 'deployment_value' + assert response.preview_mode == config.Preview.PreviewMode.DEFAULT + assert response.service_account == 'service_account_value' + assert response.artifacts_gcs_bucket == 'artifacts_gcs_bucket_value' + assert response.worker_pool == 'worker_pool_value' + assert response.error_code == config.Preview.ErrorCode.CLOUD_BUILD_PERMISSION_DENIED + assert response.build == 'build_value' + assert response.error_logs == 'error_logs_value' + assert response.logs == 'logs_value' + assert response.tf_version == 'tf_version_value' + assert response.tf_version_constraint == 'tf_version_constraint_value' + + +def test_get_preview_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 = ConfigClient( + 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 = config.GetPreviewRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_preview), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_preview(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == config.GetPreviewRequest( + name='name_value', + ) + +def test_get_preview_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create 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 = ConfigClient( + 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_preview in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_preview] = mock_rpc + request = {} + client.get_preview(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_preview(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_preview_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 = ConfigAsyncClient( + 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_preview 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_preview] = mock_rpc + + request = {} + await client.get_preview(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_preview(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_preview_async(transport: str = 'grpc_asyncio', request_type=config.GetPreviewRequest): + client = ConfigAsyncClient( + 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_preview), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(config.Preview( + name='name_value', + state=config.Preview.State.CREATING, + deployment='deployment_value', + preview_mode=config.Preview.PreviewMode.DEFAULT, + service_account='service_account_value', + artifacts_gcs_bucket='artifacts_gcs_bucket_value', + worker_pool='worker_pool_value', + error_code=config.Preview.ErrorCode.CLOUD_BUILD_PERMISSION_DENIED, + build='build_value', + error_logs='error_logs_value', + logs='logs_value', + tf_version='tf_version_value', + tf_version_constraint='tf_version_constraint_value', + )) + response = await client.get_preview(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = config.GetPreviewRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, config.Preview) + assert response.name == 'name_value' + assert response.state == config.Preview.State.CREATING + assert response.deployment == 'deployment_value' + assert response.preview_mode == config.Preview.PreviewMode.DEFAULT + assert response.service_account == 'service_account_value' + assert response.artifacts_gcs_bucket == 'artifacts_gcs_bucket_value' + assert response.worker_pool == 'worker_pool_value' + assert response.error_code == config.Preview.ErrorCode.CLOUD_BUILD_PERMISSION_DENIED + assert response.build == 'build_value' + assert response.error_logs == 'error_logs_value' + assert response.logs == 'logs_value' + assert response.tf_version == 'tf_version_value' + assert response.tf_version_constraint == 'tf_version_constraint_value' + + +@pytest.mark.asyncio +async def test_get_preview_async_from_dict(): + await test_get_preview_async(request_type=dict) + +def test_get_preview_field_headers(): + client = ConfigClient( + 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 = config.GetPreviewRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_preview), + '__call__') as call: + call.return_value = config.Preview() + client.get_preview(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_preview_field_headers_async(): + client = ConfigAsyncClient( + 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 = config.GetPreviewRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_preview), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.Preview()) + await client.get_preview(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_preview_flattened(): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_preview), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = config.Preview() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_preview( + 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_preview_flattened_error(): + client = ConfigClient( + 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_preview( + config.GetPreviewRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_preview_flattened_async(): + client = ConfigAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_preview), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = config.Preview() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.Preview()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_preview( + 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_preview_flattened_error_async(): + client = ConfigAsyncClient( + 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_preview( + config.GetPreviewRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + config.ListPreviewsRequest, + dict, +]) +def test_list_previews(request_type, transport: str = 'grpc'): + client = ConfigClient( + 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_previews), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = config.ListPreviewsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + response = client.list_previews(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = config.ListPreviewsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListPreviewsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_previews_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 = ConfigClient( + 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 = config.ListPreviewsRequest( + 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_previews), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_previews(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == config.ListPreviewsRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + order_by='order_by_value', + ) + +def test_list_previews_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create 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 = ConfigClient( + 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_previews in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_previews] = mock_rpc + request = {} + client.list_previews(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_previews(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_previews_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 = ConfigAsyncClient( + 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_previews 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_previews] = mock_rpc + + request = {} + await client.list_previews(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_previews(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_previews_async(transport: str = 'grpc_asyncio', request_type=config.ListPreviewsRequest): + client = ConfigAsyncClient( + 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_previews), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(config.ListPreviewsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_previews(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = config.ListPreviewsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListPreviewsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.asyncio +async def test_list_previews_async_from_dict(): + await test_list_previews_async(request_type=dict) + +def test_list_previews_field_headers(): + client = ConfigClient( + 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 = config.ListPreviewsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_previews), + '__call__') as call: + call.return_value = config.ListPreviewsResponse() + client.list_previews(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_previews_field_headers_async(): + client = ConfigAsyncClient( + 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 = config.ListPreviewsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_previews), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.ListPreviewsResponse()) + await client.list_previews(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_previews_flattened(): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_previews), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = config.ListPreviewsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_previews( + 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_previews_flattened_error(): + client = ConfigClient( + 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_previews( + config.ListPreviewsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_previews_flattened_async(): + client = ConfigAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_previews), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = config.ListPreviewsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.ListPreviewsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_previews( + 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_previews_flattened_error_async(): + client = ConfigAsyncClient( + 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_previews( + config.ListPreviewsRequest(), + parent='parent_value', + ) + + +def test_list_previews_pager(transport_name: str = "grpc"): + client = ConfigClient( + 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_previews), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + config.ListPreviewsResponse( + previews=[ + config.Preview(), + config.Preview(), + config.Preview(), + ], + next_page_token='abc', + ), + config.ListPreviewsResponse( + previews=[], + next_page_token='def', + ), + config.ListPreviewsResponse( + previews=[ + config.Preview(), + ], + next_page_token='ghi', + ), + config.ListPreviewsResponse( + previews=[ + config.Preview(), + config.Preview(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_previews(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, config.Preview) + for i in results) +def test_list_previews_pages(transport_name: str = "grpc"): + client = ConfigClient( + 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_previews), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + config.ListPreviewsResponse( + previews=[ + config.Preview(), + config.Preview(), + config.Preview(), + ], + next_page_token='abc', + ), + config.ListPreviewsResponse( + previews=[], + next_page_token='def', + ), + config.ListPreviewsResponse( + previews=[ + config.Preview(), + ], + next_page_token='ghi', + ), + config.ListPreviewsResponse( + previews=[ + config.Preview(), + config.Preview(), + ], + ), + RuntimeError, + ) + pages = list(client.list_previews(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_previews_async_pager(): + client = ConfigAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_previews), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + config.ListPreviewsResponse( + previews=[ + config.Preview(), + config.Preview(), + config.Preview(), + ], + next_page_token='abc', + ), + config.ListPreviewsResponse( + previews=[], + next_page_token='def', + ), + config.ListPreviewsResponse( + previews=[ + config.Preview(), + ], + next_page_token='ghi', + ), + config.ListPreviewsResponse( + previews=[ + config.Preview(), + config.Preview(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_previews(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, config.Preview) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_previews_async_pages(): + client = ConfigAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_previews), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + config.ListPreviewsResponse( + previews=[ + config.Preview(), + config.Preview(), + config.Preview(), + ], + next_page_token='abc', + ), + config.ListPreviewsResponse( + previews=[], + next_page_token='def', + ), + config.ListPreviewsResponse( + previews=[ + config.Preview(), + ], + next_page_token='ghi', + ), + config.ListPreviewsResponse( + previews=[ + config.Preview(), + config.Preview(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_previews(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", [ + config.DeletePreviewRequest, + dict, +]) +def test_delete_preview(request_type, transport: str = 'grpc'): + client = ConfigClient( + 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_preview), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_preview(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = config.DeletePreviewRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_preview_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 = ConfigClient( + 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 = config.DeletePreviewRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_preview), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_preview(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == config.DeletePreviewRequest( + name='name_value', + ) + +def test_delete_preview_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create 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 = ConfigClient( + 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_preview in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_preview] = mock_rpc + request = {} + client.delete_preview(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_preview(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_preview_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 = ConfigAsyncClient( + 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_preview 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_preview] = mock_rpc + + request = {} + await client.delete_preview(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_preview(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_preview_async(transport: str = 'grpc_asyncio', request_type=config.DeletePreviewRequest): + client = ConfigAsyncClient( + 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_preview), + '__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_preview(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = config.DeletePreviewRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_preview_async_from_dict(): + await test_delete_preview_async(request_type=dict) + +def test_delete_preview_field_headers(): + client = ConfigClient( + 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 = config.DeletePreviewRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_preview), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_preview(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_preview_field_headers_async(): + client = ConfigAsyncClient( + 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 = config.DeletePreviewRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_preview), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_preview(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_preview_flattened(): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_preview), + '__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_preview( + 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_preview_flattened_error(): + client = ConfigClient( + 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_preview( + config.DeletePreviewRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_preview_flattened_async(): + client = ConfigAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_preview), + '__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_preview( + 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_preview_flattened_error_async(): + client = ConfigAsyncClient( + 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_preview( + config.DeletePreviewRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + config.ExportPreviewResultRequest, + dict, +]) +def test_export_preview_result(request_type, transport: str = 'grpc'): + client = ConfigClient( + 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.export_preview_result), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = config.ExportPreviewResultResponse( + ) + response = client.export_preview_result(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = config.ExportPreviewResultRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, config.ExportPreviewResultResponse) + + +def test_export_preview_result_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 = ConfigClient( + 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 = config.ExportPreviewResultRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.export_preview_result), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.export_preview_result(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == config.ExportPreviewResultRequest( + parent='parent_value', + ) + +def test_export_preview_result_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create 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 = ConfigClient( + 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.export_preview_result in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.export_preview_result] = mock_rpc + request = {} + client.export_preview_result(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.export_preview_result(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_export_preview_result_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 = ConfigAsyncClient( + 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.export_preview_result 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.export_preview_result] = mock_rpc + + request = {} + await client.export_preview_result(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.export_preview_result(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_export_preview_result_async(transport: str = 'grpc_asyncio', request_type=config.ExportPreviewResultRequest): + client = ConfigAsyncClient( + 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.export_preview_result), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(config.ExportPreviewResultResponse( + )) + response = await client.export_preview_result(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = config.ExportPreviewResultRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, config.ExportPreviewResultResponse) + + +@pytest.mark.asyncio +async def test_export_preview_result_async_from_dict(): + await test_export_preview_result_async(request_type=dict) + +def test_export_preview_result_field_headers(): + client = ConfigClient( + 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 = config.ExportPreviewResultRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.export_preview_result), + '__call__') as call: + call.return_value = config.ExportPreviewResultResponse() + client.export_preview_result(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_export_preview_result_field_headers_async(): + client = ConfigAsyncClient( + 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 = config.ExportPreviewResultRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.export_preview_result), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.ExportPreviewResultResponse()) + await client.export_preview_result(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'] + + +@pytest.mark.parametrize("request_type", [ + config.ListTerraformVersionsRequest, + dict, +]) +def test_list_terraform_versions(request_type, transport: str = 'grpc'): + client = ConfigClient( + 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_terraform_versions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = config.ListTerraformVersionsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + response = client.list_terraform_versions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = config.ListTerraformVersionsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListTerraformVersionsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_terraform_versions_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 = ConfigClient( + 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 = config.ListTerraformVersionsRequest( + 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_terraform_versions), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_terraform_versions(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == config.ListTerraformVersionsRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + order_by='order_by_value', + ) + +def test_list_terraform_versions_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create 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 = ConfigClient( + 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_terraform_versions in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_terraform_versions] = mock_rpc + request = {} + client.list_terraform_versions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_terraform_versions(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_terraform_versions_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 = ConfigAsyncClient( + 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_terraform_versions 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_terraform_versions] = mock_rpc + + request = {} + await client.list_terraform_versions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_terraform_versions(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_terraform_versions_async(transport: str = 'grpc_asyncio', request_type=config.ListTerraformVersionsRequest): + client = ConfigAsyncClient( + 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_terraform_versions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(config.ListTerraformVersionsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_terraform_versions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = config.ListTerraformVersionsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListTerraformVersionsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.asyncio +async def test_list_terraform_versions_async_from_dict(): + await test_list_terraform_versions_async(request_type=dict) + +def test_list_terraform_versions_field_headers(): + client = ConfigClient( + 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 = config.ListTerraformVersionsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_terraform_versions), + '__call__') as call: + call.return_value = config.ListTerraformVersionsResponse() + client.list_terraform_versions(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_terraform_versions_field_headers_async(): + client = ConfigAsyncClient( + 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 = config.ListTerraformVersionsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_terraform_versions), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.ListTerraformVersionsResponse()) + await client.list_terraform_versions(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_terraform_versions_flattened(): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_terraform_versions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = config.ListTerraformVersionsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_terraform_versions( + 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_terraform_versions_flattened_error(): + client = ConfigClient( + 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_terraform_versions( + config.ListTerraformVersionsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_terraform_versions_flattened_async(): + client = ConfigAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_terraform_versions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = config.ListTerraformVersionsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.ListTerraformVersionsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_terraform_versions( + 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_terraform_versions_flattened_error_async(): + client = ConfigAsyncClient( + 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_terraform_versions( + config.ListTerraformVersionsRequest(), + parent='parent_value', + ) + + +def test_list_terraform_versions_pager(transport_name: str = "grpc"): + client = ConfigClient( + 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_terraform_versions), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + config.ListTerraformVersionsResponse( + terraform_versions=[ + config.TerraformVersion(), + config.TerraformVersion(), + config.TerraformVersion(), + ], + next_page_token='abc', + ), + config.ListTerraformVersionsResponse( + terraform_versions=[], + next_page_token='def', + ), + config.ListTerraformVersionsResponse( + terraform_versions=[ + config.TerraformVersion(), + ], + next_page_token='ghi', + ), + config.ListTerraformVersionsResponse( + terraform_versions=[ + config.TerraformVersion(), + config.TerraformVersion(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_terraform_versions(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, config.TerraformVersion) + for i in results) +def test_list_terraform_versions_pages(transport_name: str = "grpc"): + client = ConfigClient( + 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_terraform_versions), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + config.ListTerraformVersionsResponse( + terraform_versions=[ + config.TerraformVersion(), + config.TerraformVersion(), + config.TerraformVersion(), + ], + next_page_token='abc', + ), + config.ListTerraformVersionsResponse( + terraform_versions=[], + next_page_token='def', + ), + config.ListTerraformVersionsResponse( + terraform_versions=[ + config.TerraformVersion(), + ], + next_page_token='ghi', + ), + config.ListTerraformVersionsResponse( + terraform_versions=[ + config.TerraformVersion(), + config.TerraformVersion(), + ], + ), + RuntimeError, + ) + pages = list(client.list_terraform_versions(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_terraform_versions_async_pager(): + client = ConfigAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_terraform_versions), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + config.ListTerraformVersionsResponse( + terraform_versions=[ + config.TerraformVersion(), + config.TerraformVersion(), + config.TerraformVersion(), + ], + next_page_token='abc', + ), + config.ListTerraformVersionsResponse( + terraform_versions=[], + next_page_token='def', + ), + config.ListTerraformVersionsResponse( + terraform_versions=[ + config.TerraformVersion(), + ], + next_page_token='ghi', + ), + config.ListTerraformVersionsResponse( + terraform_versions=[ + config.TerraformVersion(), + config.TerraformVersion(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_terraform_versions(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, config.TerraformVersion) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_terraform_versions_async_pages(): + client = ConfigAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_terraform_versions), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + config.ListTerraformVersionsResponse( + terraform_versions=[ + config.TerraformVersion(), + config.TerraformVersion(), + config.TerraformVersion(), + ], + next_page_token='abc', + ), + config.ListTerraformVersionsResponse( + terraform_versions=[], + next_page_token='def', + ), + config.ListTerraformVersionsResponse( + terraform_versions=[ + config.TerraformVersion(), + ], + next_page_token='ghi', + ), + config.ListTerraformVersionsResponse( + terraform_versions=[ + config.TerraformVersion(), + config.TerraformVersion(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_terraform_versions(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", [ + config.GetTerraformVersionRequest, + dict, +]) +def test_get_terraform_version(request_type, transport: str = 'grpc'): + client = ConfigClient( + 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_terraform_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = config.TerraformVersion( + name='name_value', + state=config.TerraformVersion.State.ACTIVE, + ) + response = client.get_terraform_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = config.GetTerraformVersionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, config.TerraformVersion) + assert response.name == 'name_value' + assert response.state == config.TerraformVersion.State.ACTIVE + + +def test_get_terraform_version_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 = ConfigClient( + 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 = config.GetTerraformVersionRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_terraform_version), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_terraform_version(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == config.GetTerraformVersionRequest( + name='name_value', + ) + +def test_get_terraform_version_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create 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 = ConfigClient( + 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_terraform_version in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_terraform_version] = mock_rpc + request = {} + client.get_terraform_version(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_terraform_version(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_terraform_version_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 = ConfigAsyncClient( + 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_terraform_version 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_terraform_version] = mock_rpc + + request = {} + await client.get_terraform_version(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_terraform_version(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_terraform_version_async(transport: str = 'grpc_asyncio', request_type=config.GetTerraformVersionRequest): + client = ConfigAsyncClient( + 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_terraform_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(config.TerraformVersion( + name='name_value', + state=config.TerraformVersion.State.ACTIVE, + )) + response = await client.get_terraform_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = config.GetTerraformVersionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, config.TerraformVersion) + assert response.name == 'name_value' + assert response.state == config.TerraformVersion.State.ACTIVE + + +@pytest.mark.asyncio +async def test_get_terraform_version_async_from_dict(): + await test_get_terraform_version_async(request_type=dict) + +def test_get_terraform_version_field_headers(): + client = ConfigClient( + 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 = config.GetTerraformVersionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_terraform_version), + '__call__') as call: + call.return_value = config.TerraformVersion() + client.get_terraform_version(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_terraform_version_field_headers_async(): + client = ConfigAsyncClient( + 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 = config.GetTerraformVersionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_terraform_version), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.TerraformVersion()) + await client.get_terraform_version(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_terraform_version_flattened(): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_terraform_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = config.TerraformVersion() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_terraform_version( + 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_terraform_version_flattened_error(): + client = ConfigClient( + 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_terraform_version( + config.GetTerraformVersionRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_terraform_version_flattened_async(): + client = ConfigAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_terraform_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = config.TerraformVersion() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.TerraformVersion()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_terraform_version( + 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_terraform_version_flattened_error_async(): + client = ConfigAsyncClient( + 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_terraform_version( + config.GetTerraformVersionRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + config.ListResourceChangesRequest, + dict, +]) +def test_list_resource_changes(request_type, transport: str = 'grpc'): + client = ConfigClient( + 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_changes), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = config.ListResourceChangesResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + response = client.list_resource_changes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = config.ListResourceChangesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListResourceChangesPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_resource_changes_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 = ConfigClient( + 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 = config.ListResourceChangesRequest( + 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_changes), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_resource_changes(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == config.ListResourceChangesRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + order_by='order_by_value', + ) + +def test_list_resource_changes_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create 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 = ConfigClient( + 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_changes in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_changes] = mock_rpc + request = {} + client.list_resource_changes(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_resource_changes(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_changes_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 = ConfigAsyncClient( + 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_changes 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_changes] = mock_rpc + + request = {} + await client.list_resource_changes(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_resource_changes(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_changes_async(transport: str = 'grpc_asyncio', request_type=config.ListResourceChangesRequest): + client = ConfigAsyncClient( + 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_changes), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(config.ListResourceChangesResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_resource_changes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = config.ListResourceChangesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListResourceChangesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.asyncio +async def test_list_resource_changes_async_from_dict(): + await test_list_resource_changes_async(request_type=dict) + +def test_list_resource_changes_field_headers(): + client = ConfigClient( + 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 = config.ListResourceChangesRequest() + + 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_changes), + '__call__') as call: + call.return_value = config.ListResourceChangesResponse() + client.list_resource_changes(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_changes_field_headers_async(): + client = ConfigAsyncClient( + 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 = config.ListResourceChangesRequest() + + 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_changes), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.ListResourceChangesResponse()) + await client.list_resource_changes(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_changes_flattened(): + client = ConfigClient( + 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_changes), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = config.ListResourceChangesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_resource_changes( + 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_changes_flattened_error(): + client = ConfigClient( + 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_changes( + config.ListResourceChangesRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_resource_changes_flattened_async(): + client = ConfigAsyncClient( + 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_changes), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = config.ListResourceChangesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.ListResourceChangesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_resource_changes( + 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_changes_flattened_error_async(): + client = ConfigAsyncClient( + 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_changes( + config.ListResourceChangesRequest(), + parent='parent_value', + ) + + +def test_list_resource_changes_pager(transport_name: str = "grpc"): + client = ConfigClient( + 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_changes), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + config.ListResourceChangesResponse( + resource_changes=[ + config.ResourceChange(), + config.ResourceChange(), + config.ResourceChange(), + ], + next_page_token='abc', + ), + config.ListResourceChangesResponse( + resource_changes=[], + next_page_token='def', + ), + config.ListResourceChangesResponse( + resource_changes=[ + config.ResourceChange(), + ], + next_page_token='ghi', + ), + config.ListResourceChangesResponse( + resource_changes=[ + config.ResourceChange(), + config.ResourceChange(), + ], + ), + 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_changes(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, config.ResourceChange) + for i in results) +def test_list_resource_changes_pages(transport_name: str = "grpc"): + client = ConfigClient( + 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_changes), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + config.ListResourceChangesResponse( + resource_changes=[ + config.ResourceChange(), + config.ResourceChange(), + config.ResourceChange(), + ], + next_page_token='abc', + ), + config.ListResourceChangesResponse( + resource_changes=[], + next_page_token='def', + ), + config.ListResourceChangesResponse( + resource_changes=[ + config.ResourceChange(), + ], + next_page_token='ghi', + ), + config.ListResourceChangesResponse( + resource_changes=[ + config.ResourceChange(), + config.ResourceChange(), + ], + ), + RuntimeError, + ) + pages = list(client.list_resource_changes(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_changes_async_pager(): + client = ConfigAsyncClient( + 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_changes), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + config.ListResourceChangesResponse( + resource_changes=[ + config.ResourceChange(), + config.ResourceChange(), + config.ResourceChange(), + ], + next_page_token='abc', + ), + config.ListResourceChangesResponse( + resource_changes=[], + next_page_token='def', + ), + config.ListResourceChangesResponse( + resource_changes=[ + config.ResourceChange(), + ], + next_page_token='ghi', + ), + config.ListResourceChangesResponse( + resource_changes=[ + config.ResourceChange(), + config.ResourceChange(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_resource_changes(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, config.ResourceChange) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_resource_changes_async_pages(): + client = ConfigAsyncClient( + 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_changes), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + config.ListResourceChangesResponse( + resource_changes=[ + config.ResourceChange(), + config.ResourceChange(), + config.ResourceChange(), + ], + next_page_token='abc', + ), + config.ListResourceChangesResponse( + resource_changes=[], + next_page_token='def', + ), + config.ListResourceChangesResponse( + resource_changes=[ + config.ResourceChange(), + ], + next_page_token='ghi', + ), + config.ListResourceChangesResponse( + resource_changes=[ + config.ResourceChange(), + config.ResourceChange(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_resource_changes(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", [ + config.GetResourceChangeRequest, + dict, +]) +def test_get_resource_change(request_type, transport: str = 'grpc'): + client = ConfigClient( + 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_resource_change), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = config.ResourceChange( + name='name_value', + intent=config.ResourceChange.Intent.CREATE, + ) + response = client.get_resource_change(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = config.GetResourceChangeRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, config.ResourceChange) + assert response.name == 'name_value' + assert response.intent == config.ResourceChange.Intent.CREATE + + +def test_get_resource_change_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 = ConfigClient( + 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 = config.GetResourceChangeRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_resource_change), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_resource_change(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == config.GetResourceChangeRequest( + name='name_value', + ) + +def test_get_resource_change_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create 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 = ConfigClient( + 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_resource_change in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_change] = mock_rpc + request = {} + client.get_resource_change(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_resource_change(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_resource_change_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 = ConfigAsyncClient( + 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_resource_change 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_resource_change] = mock_rpc + + request = {} + await client.get_resource_change(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_resource_change(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_resource_change_async(transport: str = 'grpc_asyncio', request_type=config.GetResourceChangeRequest): + client = ConfigAsyncClient( + 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_resource_change), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(config.ResourceChange( + name='name_value', + intent=config.ResourceChange.Intent.CREATE, + )) + response = await client.get_resource_change(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = config.GetResourceChangeRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, config.ResourceChange) + assert response.name == 'name_value' + assert response.intent == config.ResourceChange.Intent.CREATE + + +@pytest.mark.asyncio +async def test_get_resource_change_async_from_dict(): + await test_get_resource_change_async(request_type=dict) + +def test_get_resource_change_field_headers(): + client = ConfigClient( + 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 = config.GetResourceChangeRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_resource_change), + '__call__') as call: + call.return_value = config.ResourceChange() + client.get_resource_change(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_resource_change_field_headers_async(): + client = ConfigAsyncClient( + 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 = config.GetResourceChangeRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_resource_change), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.ResourceChange()) + await client.get_resource_change(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_resource_change_flattened(): + client = ConfigClient( + 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_change), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = config.ResourceChange() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_resource_change( + 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_resource_change_flattened_error(): + client = ConfigClient( + 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_resource_change( + config.GetResourceChangeRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_resource_change_flattened_async(): + client = ConfigAsyncClient( + 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_change), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = config.ResourceChange() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.ResourceChange()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_resource_change( + 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_resource_change_flattened_error_async(): + client = ConfigAsyncClient( + 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_resource_change( + config.GetResourceChangeRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + config.ListResourceDriftsRequest, + dict, +]) +def test_list_resource_drifts(request_type, transport: str = 'grpc'): + client = ConfigClient( + 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_drifts), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = config.ListResourceDriftsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + ) + response = client.list_resource_drifts(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = config.ListResourceDriftsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListResourceDriftsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +def test_list_resource_drifts_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 = ConfigClient( + 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 = config.ListResourceDriftsRequest( + 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_drifts), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_resource_drifts(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == config.ListResourceDriftsRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + order_by='order_by_value', + ) + +def test_list_resource_drifts_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create 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 = ConfigClient( + 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_drifts in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_drifts] = mock_rpc + request = {} + client.list_resource_drifts(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_resource_drifts(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_drifts_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 = ConfigAsyncClient( + 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_drifts 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_drifts] = mock_rpc + + request = {} + await client.list_resource_drifts(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_resource_drifts(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_drifts_async(transport: str = 'grpc_asyncio', request_type=config.ListResourceDriftsRequest): + client = ConfigAsyncClient( + 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_drifts), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(config.ListResourceDriftsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + response = await client.list_resource_drifts(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = config.ListResourceDriftsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListResourceDriftsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.asyncio +async def test_list_resource_drifts_async_from_dict(): + await test_list_resource_drifts_async(request_type=dict) + +def test_list_resource_drifts_field_headers(): + client = ConfigClient( + 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 = config.ListResourceDriftsRequest() + + 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_drifts), + '__call__') as call: + call.return_value = config.ListResourceDriftsResponse() + client.list_resource_drifts(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_drifts_field_headers_async(): + client = ConfigAsyncClient( + 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 = config.ListResourceDriftsRequest() + + 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_drifts), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.ListResourceDriftsResponse()) + await client.list_resource_drifts(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_drifts_flattened(): + client = ConfigClient( + 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_drifts), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = config.ListResourceDriftsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_resource_drifts( + 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_drifts_flattened_error(): + client = ConfigClient( + 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_drifts( + config.ListResourceDriftsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_resource_drifts_flattened_async(): + client = ConfigAsyncClient( + 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_drifts), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = config.ListResourceDriftsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.ListResourceDriftsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_resource_drifts( + 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_drifts_flattened_error_async(): + client = ConfigAsyncClient( + 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_drifts( + config.ListResourceDriftsRequest(), + parent='parent_value', + ) + + +def test_list_resource_drifts_pager(transport_name: str = "grpc"): + client = ConfigClient( + 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_drifts), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + config.ListResourceDriftsResponse( + resource_drifts=[ + config.ResourceDrift(), + config.ResourceDrift(), + config.ResourceDrift(), + ], + next_page_token='abc', + ), + config.ListResourceDriftsResponse( + resource_drifts=[], + next_page_token='def', + ), + config.ListResourceDriftsResponse( + resource_drifts=[ + config.ResourceDrift(), + ], + next_page_token='ghi', + ), + config.ListResourceDriftsResponse( + resource_drifts=[ + config.ResourceDrift(), + config.ResourceDrift(), + ], + ), + 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_drifts(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, config.ResourceDrift) + for i in results) +def test_list_resource_drifts_pages(transport_name: str = "grpc"): + client = ConfigClient( + 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_drifts), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + config.ListResourceDriftsResponse( + resource_drifts=[ + config.ResourceDrift(), + config.ResourceDrift(), + config.ResourceDrift(), + ], + next_page_token='abc', + ), + config.ListResourceDriftsResponse( + resource_drifts=[], + next_page_token='def', + ), + config.ListResourceDriftsResponse( + resource_drifts=[ + config.ResourceDrift(), + ], + next_page_token='ghi', + ), + config.ListResourceDriftsResponse( + resource_drifts=[ + config.ResourceDrift(), + config.ResourceDrift(), + ], + ), + RuntimeError, + ) + pages = list(client.list_resource_drifts(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_drifts_async_pager(): + client = ConfigAsyncClient( + 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_drifts), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + config.ListResourceDriftsResponse( + resource_drifts=[ + config.ResourceDrift(), + config.ResourceDrift(), + config.ResourceDrift(), + ], + next_page_token='abc', + ), + config.ListResourceDriftsResponse( + resource_drifts=[], + next_page_token='def', + ), + config.ListResourceDriftsResponse( + resource_drifts=[ + config.ResourceDrift(), + ], + next_page_token='ghi', + ), + config.ListResourceDriftsResponse( + resource_drifts=[ + config.ResourceDrift(), + config.ResourceDrift(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_resource_drifts(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, config.ResourceDrift) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_resource_drifts_async_pages(): + client = ConfigAsyncClient( + 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_drifts), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + config.ListResourceDriftsResponse( + resource_drifts=[ + config.ResourceDrift(), + config.ResourceDrift(), + config.ResourceDrift(), + ], + next_page_token='abc', + ), + config.ListResourceDriftsResponse( + resource_drifts=[], + next_page_token='def', + ), + config.ListResourceDriftsResponse( + resource_drifts=[ + config.ResourceDrift(), + ], + next_page_token='ghi', + ), + config.ListResourceDriftsResponse( + resource_drifts=[ + config.ResourceDrift(), + config.ResourceDrift(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_resource_drifts(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", [ + config.GetResourceDriftRequest, + dict, +]) +def test_get_resource_drift(request_type, transport: str = 'grpc'): + client = ConfigClient( + 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_resource_drift), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = config.ResourceDrift( + name='name_value', + ) + response = client.get_resource_drift(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = config.GetResourceDriftRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, config.ResourceDrift) + assert response.name == 'name_value' + + +def test_get_resource_drift_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 = ConfigClient( + 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 = config.GetResourceDriftRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_resource_drift), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_resource_drift(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == config.GetResourceDriftRequest( + name='name_value', + ) + +def test_get_resource_drift_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create 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 = ConfigClient( + 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_resource_drift in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_drift] = mock_rpc + request = {} + client.get_resource_drift(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_resource_drift(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_resource_drift_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 = ConfigAsyncClient( + 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_resource_drift 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_resource_drift] = mock_rpc + + request = {} + await client.get_resource_drift(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_resource_drift(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_resource_drift_async(transport: str = 'grpc_asyncio', request_type=config.GetResourceDriftRequest): + client = ConfigAsyncClient( + 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_resource_drift), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(config.ResourceDrift( + name='name_value', + )) + response = await client.get_resource_drift(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = config.GetResourceDriftRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, config.ResourceDrift) + assert response.name == 'name_value' + + +@pytest.mark.asyncio +async def test_get_resource_drift_async_from_dict(): + await test_get_resource_drift_async(request_type=dict) + +def test_get_resource_drift_field_headers(): + client = ConfigClient( + 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 = config.GetResourceDriftRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_resource_drift), + '__call__') as call: + call.return_value = config.ResourceDrift() + client.get_resource_drift(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_resource_drift_field_headers_async(): + client = ConfigAsyncClient( + 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 = config.GetResourceDriftRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_resource_drift), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.ResourceDrift()) + await client.get_resource_drift(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_resource_drift_flattened(): + client = ConfigClient( + 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_drift), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = config.ResourceDrift() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_resource_drift( + 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_resource_drift_flattened_error(): + client = ConfigClient( + 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_resource_drift( + config.GetResourceDriftRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_resource_drift_flattened_async(): + client = ConfigAsyncClient( + 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_drift), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = config.ResourceDrift() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.ResourceDrift()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_resource_drift( + 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_resource_drift_flattened_error_async(): + client = ConfigAsyncClient( + 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_resource_drift( + config.GetResourceDriftRequest(), + name='name_value', + ) + + +def test_list_deployments_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 = ConfigClient( + 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_deployments in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_deployments] = mock_rpc + + request = {} + client.list_deployments(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_deployments(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_deployments_rest_required_fields(request_type=config.ListDeploymentsRequest): + transport_class = transports.ConfigRestTransport + + 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 + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_deployments._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_deployments._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("filter", "order_by", "page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = config.ListDeploymentsResponse() + # 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 = config.ListDeploymentsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_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_deployments(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_deployments_rest_unset_required_fields(): + transport = transports.ConfigRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_deployments._get_unset_required_fields({}) + assert set(unset_fields) == (set(("filter", "orderBy", "pageSize", "pageToken", )) & set(("parent", ))) + + +def test_list_deployments_rest_flattened(): + client = ConfigClient( + 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 = config.ListDeploymentsResponse() + + # 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 = config.ListDeploymentsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_deployments(**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/*}/deployments" % client.transport._host, args[1]) + + +def test_list_deployments_rest_flattened_error(transport: str = 'rest'): + client = ConfigClient( + 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_deployments( + config.ListDeploymentsRequest(), + parent='parent_value', + ) + + +def test_list_deployments_rest_pager(transport: str = 'rest'): + client = ConfigClient( + 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 = ( + config.ListDeploymentsResponse( + deployments=[ + config.Deployment(), + config.Deployment(), + config.Deployment(), + ], + next_page_token='abc', + ), + config.ListDeploymentsResponse( + deployments=[], + next_page_token='def', + ), + config.ListDeploymentsResponse( + deployments=[ + config.Deployment(), + ], + next_page_token='ghi', + ), + config.ListDeploymentsResponse( + deployments=[ + config.Deployment(), + config.Deployment(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(config.ListDeploymentsResponse.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_deployments(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, config.Deployment) + for i in results) + + pages = list(client.list_deployments(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_get_deployment_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 = ConfigClient( + 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_deployment in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_deployment] = mock_rpc + + request = {} + client.get_deployment(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_deployment(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_deployment_rest_required_fields(request_type=config.GetDeploymentRequest): + transport_class = transports.ConfigRestTransport + + 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 + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_deployment._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_deployment._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = config.Deployment() + # 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 = config.Deployment.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_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_deployment(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_deployment_rest_unset_required_fields(): + transport = transports.ConfigRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_deployment._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_deployment_rest_flattened(): + client = ConfigClient( + 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 = config.Deployment() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/deployments/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 = config.Deployment.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_deployment(**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/*/deployments/*}" % client.transport._host, args[1]) + + +def test_get_deployment_rest_flattened_error(transport: str = 'rest'): + client = ConfigClient( + 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_deployment( + config.GetDeploymentRequest(), + name='name_value', + ) + + +def test_create_deployment_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 = ConfigClient( + 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_deployment in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_deployment] = mock_rpc + + request = {} + client.create_deployment(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_deployment(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_deployment_rest_required_fields(request_type=config.CreateDeploymentRequest): + transport_class = transports.ConfigRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["deployment_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 "deploymentId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_deployment._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "deploymentId" in jsonified_request + assert jsonified_request["deploymentId"] == request_init["deployment_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["deploymentId"] = 'deployment_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_deployment._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("deployment_id", "request_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "deploymentId" in jsonified_request + assert jsonified_request["deploymentId"] == 'deployment_id_value' + + client = ConfigClient( + 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_deployment(request) + + expected_params = [ + ( + "deploymentId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_deployment_rest_unset_required_fields(): + transport = transports.ConfigRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_deployment._get_unset_required_fields({}) + assert set(unset_fields) == (set(("deploymentId", "requestId", )) & set(("parent", "deploymentId", "deployment", ))) + + +def test_create_deployment_rest_flattened(): + client = ConfigClient( + 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', + deployment=config.Deployment(terraform_blueprint=config.TerraformBlueprint(gcs_source='gcs_source_value')), + deployment_id='deployment_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_deployment(**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/*}/deployments" % client.transport._host, args[1]) + + +def test_create_deployment_rest_flattened_error(transport: str = 'rest'): + client = ConfigClient( + 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_deployment( + config.CreateDeploymentRequest(), + parent='parent_value', + deployment=config.Deployment(terraform_blueprint=config.TerraformBlueprint(gcs_source='gcs_source_value')), + deployment_id='deployment_id_value', + ) + + +def test_update_deployment_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 = ConfigClient( + 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_deployment in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_deployment] = mock_rpc + + request = {} + client.update_deployment(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_deployment(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_deployment_rest_required_fields(request_type=config.UpdateDeploymentRequest): + transport_class = transports.ConfigRestTransport + + 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 + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_deployment._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_deployment._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id", "update_mask", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = ConfigClient( + 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_deployment(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_deployment_rest_unset_required_fields(): + transport = transports.ConfigRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_deployment._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId", "updateMask", )) & set(("deployment", ))) + + +def test_update_deployment_rest_flattened(): + client = ConfigClient( + 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 = {'deployment': {'name': 'projects/sample1/locations/sample2/deployments/sample3'}} + + # get truthy value for each flattened field + mock_args = dict( + deployment=config.Deployment(terraform_blueprint=config.TerraformBlueprint(gcs_source='gcs_source_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_deployment(**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/{deployment.name=projects/*/locations/*/deployments/*}" % client.transport._host, args[1]) + + +def test_update_deployment_rest_flattened_error(transport: str = 'rest'): + client = ConfigClient( + 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_deployment( + config.UpdateDeploymentRequest(), + deployment=config.Deployment(terraform_blueprint=config.TerraformBlueprint(gcs_source='gcs_source_value')), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_delete_deployment_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 = ConfigClient( + 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_deployment in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_deployment] = mock_rpc + + request = {} + client.delete_deployment(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_deployment(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_deployment_rest_required_fields(request_type=config.DeleteDeploymentRequest): + transport_class = transports.ConfigRestTransport + + 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 + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_deployment._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_deployment._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("delete_policy", "force", "request_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = ConfigClient( + 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_deployment(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_deployment_rest_unset_required_fields(): + transport = transports.ConfigRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_deployment._get_unset_required_fields({}) + assert set(unset_fields) == (set(("deletePolicy", "force", "requestId", )) & set(("name", ))) + + +def test_delete_deployment_rest_flattened(): + client = ConfigClient( + 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/deployments/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_deployment(**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/*/deployments/*}" % client.transport._host, args[1]) + + +def test_delete_deployment_rest_flattened_error(transport: str = 'rest'): + client = ConfigClient( + 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_deployment( + config.DeleteDeploymentRequest(), + name='name_value', + ) + + +def test_list_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 = ConfigClient( + 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_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_revisions] = mock_rpc + + request = {} + client.list_revisions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_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_revisions_rest_required_fields(request_type=config.ListRevisionsRequest): + transport_class = transports.ConfigRestTransport + + 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 + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_revisions._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_revisions._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("filter", "order_by", "page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = config.ListRevisionsResponse() + # 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 = config.ListRevisionsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_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_revisions(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_revisions_rest_unset_required_fields(): + transport = transports.ConfigRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_revisions._get_unset_required_fields({}) + assert set(unset_fields) == (set(("filter", "orderBy", "pageSize", "pageToken", )) & set(("parent", ))) + + +def test_list_revisions_rest_flattened(): + client = ConfigClient( + 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 = config.ListRevisionsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/deployments/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 = config.ListRevisionsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_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/v1/{parent=projects/*/locations/*/deployments/*}/revisions" % client.transport._host, args[1]) + + +def test_list_revisions_rest_flattened_error(transport: str = 'rest'): + client = ConfigClient( + 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_revisions( + config.ListRevisionsRequest(), + parent='parent_value', + ) + + +def test_list_revisions_rest_pager(transport: str = 'rest'): + client = ConfigClient( + 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 = ( + config.ListRevisionsResponse( + revisions=[ + config.Revision(), + config.Revision(), + config.Revision(), + ], + next_page_token='abc', + ), + config.ListRevisionsResponse( + revisions=[], + next_page_token='def', + ), + config.ListRevisionsResponse( + revisions=[ + config.Revision(), + ], + next_page_token='ghi', + ), + config.ListRevisionsResponse( + revisions=[ + config.Revision(), + config.Revision(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(config.ListRevisionsResponse.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/deployments/sample3'} + + pager = client.list_revisions(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, config.Revision) + for i in results) + + pages = list(client.list_revisions(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_get_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 = ConfigClient( + 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_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_revision] = mock_rpc + + request = {} + client.get_revision(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_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_revision_rest_required_fields(request_type=config.GetRevisionRequest): + transport_class = transports.ConfigRestTransport + + 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 + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_revision._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_revision._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = config.Revision() + # 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 = config.Revision.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_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_revision(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_revision_rest_unset_required_fields(): + transport = transports.ConfigRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_revision._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_revision_rest_flattened(): + client = ConfigClient( + 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 = config.Revision() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/deployments/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 = config.Revision.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_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/v1/{name=projects/*/locations/*/deployments/*/revisions/*}" % client.transport._host, args[1]) + + +def test_get_revision_rest_flattened_error(transport: str = 'rest'): + client = ConfigClient( + 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_revision( + config.GetRevisionRequest(), + name='name_value', + ) + + +def test_get_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 = ConfigClient( + 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 in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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] = mock_rpc + + request = {} + client.get_resource(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_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_resource_rest_required_fields(request_type=config.GetResourceRequest): + transport_class = transports.ConfigRestTransport + + 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 + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_resource._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_resource._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = config.Resource() + # 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 = config.Resource.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_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(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_resource_rest_unset_required_fields(): + transport = transports.ConfigRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_resource._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_resource_rest_flattened(): + client = ConfigClient( + 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 = config.Resource() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/deployments/sample3/revisions/sample4/resources/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 = config.Resource.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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(**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/*/deployments/*/revisions/*/resources/*}" % client.transport._host, args[1]) + + +def test_get_resource_rest_flattened_error(transport: str = 'rest'): + client = ConfigClient( + 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( + config.GetResourceRequest(), + name='name_value', + ) + + +def test_list_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 = ConfigClient( + 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_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_resources] = mock_rpc + + request = {} + client.list_resources(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_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_resources_rest_required_fields(request_type=config.ListResourcesRequest): + transport_class = transports.ConfigRestTransport + + 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 + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_resources._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_resources._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("filter", "order_by", "page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = config.ListResourcesResponse() + # 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 = config.ListResourcesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_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_resources(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_resources_rest_unset_required_fields(): + transport = transports.ConfigRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_resources._get_unset_required_fields({}) + assert set(unset_fields) == (set(("filter", "orderBy", "pageSize", "pageToken", )) & set(("parent", ))) + + +def test_list_resources_rest_flattened(): + client = ConfigClient( + 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 = config.ListResourcesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/deployments/sample3/revisions/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 = config.ListResourcesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_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/v1/{parent=projects/*/locations/*/deployments/*/revisions/*}/resources" % client.transport._host, args[1]) + + +def test_list_resources_rest_flattened_error(transport: str = 'rest'): + client = ConfigClient( + 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_resources( + config.ListResourcesRequest(), + parent='parent_value', + ) + + +def test_list_resources_rest_pager(transport: str = 'rest'): + client = ConfigClient( + 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 = ( + config.ListResourcesResponse( + resources=[ + config.Resource(), + config.Resource(), + config.Resource(), + ], + next_page_token='abc', + ), + config.ListResourcesResponse( + resources=[], + next_page_token='def', + ), + config.ListResourcesResponse( + resources=[ + config.Resource(), + ], + next_page_token='ghi', + ), + config.ListResourcesResponse( + resources=[ + config.Resource(), + config.Resource(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(config.ListResourcesResponse.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/deployments/sample3/revisions/sample4'} + + pager = client.list_resources(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, config.Resource) + for i in results) + + pages = list(client.list_resources(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_export_deployment_statefile_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 = ConfigClient( + 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.export_deployment_statefile in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.export_deployment_statefile] = mock_rpc + + request = {} + client.export_deployment_statefile(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.export_deployment_statefile(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_export_deployment_statefile_rest_required_fields(request_type=config.ExportDeploymentStatefileRequest): + transport_class = transports.ConfigRestTransport + + 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 + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).export_deployment_statefile._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).export_deployment_statefile._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = config.Statefile() + # 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 = config.Statefile.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.export_deployment_statefile(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_export_deployment_statefile_rest_unset_required_fields(): + transport = transports.ConfigRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.export_deployment_statefile._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", ))) + + +def test_export_revision_statefile_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 = ConfigClient( + 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.export_revision_statefile in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.export_revision_statefile] = mock_rpc + + request = {} + client.export_revision_statefile(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.export_revision_statefile(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_export_revision_statefile_rest_required_fields(request_type=config.ExportRevisionStatefileRequest): + transport_class = transports.ConfigRestTransport + + 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 + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).export_revision_statefile._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).export_revision_statefile._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = config.Statefile() + # 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 = config.Statefile.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.export_revision_statefile(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_export_revision_statefile_rest_unset_required_fields(): + transport = transports.ConfigRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.export_revision_statefile._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", ))) + + +def test_import_statefile_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 = ConfigClient( + 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.import_statefile in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.import_statefile] = mock_rpc + + request = {} + client.import_statefile(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.import_statefile(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_import_statefile_rest_required_fields(request_type=config.ImportStatefileRequest): + transport_class = transports.ConfigRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["lock_id"] = 0 + 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 + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).import_statefile._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + jsonified_request["lockId"] = 725 + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).import_statefile._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "lockId" in jsonified_request + assert jsonified_request["lockId"] == 725 + + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = config.Statefile() + # 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 = config.Statefile.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.import_statefile(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_import_statefile_rest_unset_required_fields(): + transport = transports.ConfigRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.import_statefile._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "lockId", ))) + + +def test_import_statefile_rest_flattened(): + client = ConfigClient( + 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 = config.Statefile() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/deployments/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + lock_id=725, + ) + 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 = config.Statefile.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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.import_statefile(**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/*/deployments/*}:importState" % client.transport._host, args[1]) + + +def test_import_statefile_rest_flattened_error(transport: str = 'rest'): + client = ConfigClient( + 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.import_statefile( + config.ImportStatefileRequest(), + parent='parent_value', + lock_id=725, + ) + + +def test_delete_statefile_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 = ConfigClient( + 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_statefile in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_statefile] = mock_rpc + + request = {} + client.delete_statefile(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_statefile(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_statefile_rest_required_fields(request_type=config.DeleteStatefileRequest): + transport_class = transports.ConfigRestTransport + + request_init = {} + request_init["name"] = "" + request_init["lock_id"] = 0 + 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 + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_statefile._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + jsonified_request["lockId"] = 725 + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_statefile._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + assert "lockId" in jsonified_request + assert jsonified_request["lockId"] == 725 + + client = ConfigClient( + 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.delete_statefile(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_statefile_rest_unset_required_fields(): + transport = transports.ConfigRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_statefile._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", "lockId", ))) + + +def test_delete_statefile_rest_flattened(): + client = ConfigClient( + 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': 'projects/sample1/locations/sample2/deployments/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 = '' + response_value._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_statefile(**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/*/deployments/*}:deleteState" % client.transport._host, args[1]) + + +def test_delete_statefile_rest_flattened_error(transport: str = 'rest'): + client = ConfigClient( + 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_statefile( + config.DeleteStatefileRequest(), + name='name_value', + ) + + +def test_lock_deployment_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 = ConfigClient( + 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.lock_deployment in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.lock_deployment] = mock_rpc + + request = {} + client.lock_deployment(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.lock_deployment(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_lock_deployment_rest_required_fields(request_type=config.LockDeploymentRequest): + transport_class = transports.ConfigRestTransport + + 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 + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).lock_deployment._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).lock_deployment._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = ConfigClient( + 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.lock_deployment(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_lock_deployment_rest_unset_required_fields(): + transport = transports.ConfigRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.lock_deployment._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_lock_deployment_rest_flattened(): + client = ConfigClient( + 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/deployments/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.lock_deployment(**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/*/deployments/*}:lock" % client.transport._host, args[1]) + + +def test_lock_deployment_rest_flattened_error(transport: str = 'rest'): + client = ConfigClient( + 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.lock_deployment( + config.LockDeploymentRequest(), + name='name_value', + ) + + +def test_unlock_deployment_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 = ConfigClient( + 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.unlock_deployment in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.unlock_deployment] = mock_rpc + + request = {} + client.unlock_deployment(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.unlock_deployment(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_unlock_deployment_rest_required_fields(request_type=config.UnlockDeploymentRequest): + transport_class = transports.ConfigRestTransport + + request_init = {} + request_init["name"] = "" + request_init["lock_id"] = 0 + 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 + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).unlock_deployment._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + jsonified_request["lockId"] = 725 + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).unlock_deployment._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + assert "lockId" in jsonified_request + assert jsonified_request["lockId"] == 725 + + client = ConfigClient( + 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.unlock_deployment(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_unlock_deployment_rest_unset_required_fields(): + transport = transports.ConfigRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.unlock_deployment._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", "lockId", ))) + + +def test_unlock_deployment_rest_flattened(): + client = ConfigClient( + 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/deployments/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + lock_id=725, + ) + 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.unlock_deployment(**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/*/deployments/*}:unlock" % client.transport._host, args[1]) + + +def test_unlock_deployment_rest_flattened_error(transport: str = 'rest'): + client = ConfigClient( + 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.unlock_deployment( + config.UnlockDeploymentRequest(), + name='name_value', + lock_id=725, + ) + + +def test_export_lock_info_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 = ConfigClient( + 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.export_lock_info in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.export_lock_info] = mock_rpc + + request = {} + client.export_lock_info(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.export_lock_info(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_export_lock_info_rest_required_fields(request_type=config.ExportLockInfoRequest): + transport_class = transports.ConfigRestTransport + + 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 + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).export_lock_info._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).export_lock_info._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = config.LockInfo() + # 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 = config.LockInfo.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.export_lock_info(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_export_lock_info_rest_unset_required_fields(): + transport = transports.ConfigRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.export_lock_info._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_export_lock_info_rest_flattened(): + client = ConfigClient( + 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 = config.LockInfo() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/deployments/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 = config.LockInfo.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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.export_lock_info(**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/*/deployments/*}:exportLock" % client.transport._host, args[1]) + + +def test_export_lock_info_rest_flattened_error(transport: str = 'rest'): + client = ConfigClient( + 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.export_lock_info( + config.ExportLockInfoRequest(), + name='name_value', + ) + + +def test_create_preview_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 = ConfigClient( + 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_preview in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_preview] = mock_rpc + + request = {} + client.create_preview(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_preview(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_preview_rest_required_fields(request_type=config.CreatePreviewRequest): + transport_class = transports.ConfigRestTransport + + 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 + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_preview._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_preview._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("preview_id", "request_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = ConfigClient( + 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_preview(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_preview_rest_unset_required_fields(): + transport = transports.ConfigRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_preview._get_unset_required_fields({}) + assert set(unset_fields) == (set(("previewId", "requestId", )) & set(("parent", "preview", ))) + + +def test_create_preview_rest_flattened(): + client = ConfigClient( + 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', + preview=config.Preview(terraform_blueprint=config.TerraformBlueprint(gcs_source='gcs_source_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_preview(**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/*}/previews" % client.transport._host, args[1]) + + +def test_create_preview_rest_flattened_error(transport: str = 'rest'): + client = ConfigClient( + 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_preview( + config.CreatePreviewRequest(), + parent='parent_value', + preview=config.Preview(terraform_blueprint=config.TerraformBlueprint(gcs_source='gcs_source_value')), + ) + + +def test_get_preview_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 = ConfigClient( + 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_preview in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_preview] = mock_rpc + + request = {} + client.get_preview(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_preview(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_preview_rest_required_fields(request_type=config.GetPreviewRequest): + transport_class = transports.ConfigRestTransport + + 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 + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_preview._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_preview._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = config.Preview() + # 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 = config.Preview.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_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_preview(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_preview_rest_unset_required_fields(): + transport = transports.ConfigRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_preview._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_preview_rest_flattened(): + client = ConfigClient( + 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 = config.Preview() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/previews/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 = config.Preview.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_preview(**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/*/previews/*}" % client.transport._host, args[1]) + + +def test_get_preview_rest_flattened_error(transport: str = 'rest'): + client = ConfigClient( + 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_preview( + config.GetPreviewRequest(), + name='name_value', + ) + + +def test_list_previews_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 = ConfigClient( + 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_previews in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_previews] = mock_rpc + + request = {} + client.list_previews(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_previews(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_previews_rest_required_fields(request_type=config.ListPreviewsRequest): + transport_class = transports.ConfigRestTransport + + 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 + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_previews._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_previews._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("filter", "order_by", "page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = config.ListPreviewsResponse() + # 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 = config.ListPreviewsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_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_previews(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_previews_rest_unset_required_fields(): + transport = transports.ConfigRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_previews._get_unset_required_fields({}) + assert set(unset_fields) == (set(("filter", "orderBy", "pageSize", "pageToken", )) & set(("parent", ))) + + +def test_list_previews_rest_flattened(): + client = ConfigClient( + 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 = config.ListPreviewsResponse() + + # 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 = config.ListPreviewsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_previews(**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/*}/previews" % client.transport._host, args[1]) + + +def test_list_previews_rest_flattened_error(transport: str = 'rest'): + client = ConfigClient( + 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_previews( + config.ListPreviewsRequest(), + parent='parent_value', + ) + + +def test_list_previews_rest_pager(transport: str = 'rest'): + client = ConfigClient( + 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 = ( + config.ListPreviewsResponse( + previews=[ + config.Preview(), + config.Preview(), + config.Preview(), + ], + next_page_token='abc', + ), + config.ListPreviewsResponse( + previews=[], + next_page_token='def', + ), + config.ListPreviewsResponse( + previews=[ + config.Preview(), + ], + next_page_token='ghi', + ), + config.ListPreviewsResponse( + previews=[ + config.Preview(), + config.Preview(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(config.ListPreviewsResponse.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_previews(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, config.Preview) + for i in results) + + pages = list(client.list_previews(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_delete_preview_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 = ConfigClient( + 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_preview in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_preview] = mock_rpc + + request = {} + client.delete_preview(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_preview(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_preview_rest_required_fields(request_type=config.DeletePreviewRequest): + transport_class = transports.ConfigRestTransport + + 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 + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_preview._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_preview._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = ConfigClient( + 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_preview(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_preview_rest_unset_required_fields(): + transport = transports.ConfigRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_preview._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId", )) & set(("name", ))) + + +def test_delete_preview_rest_flattened(): + client = ConfigClient( + 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/previews/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_preview(**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/*/previews/*}" % client.transport._host, args[1]) + + +def test_delete_preview_rest_flattened_error(transport: str = 'rest'): + client = ConfigClient( + 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_preview( + config.DeletePreviewRequest(), + name='name_value', + ) + + +def test_export_preview_result_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 = ConfigClient( + 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.export_preview_result in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.export_preview_result] = mock_rpc + + request = {} + client.export_preview_result(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.export_preview_result(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_export_preview_result_rest_required_fields(request_type=config.ExportPreviewResultRequest): + transport_class = transports.ConfigRestTransport + + 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 + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).export_preview_result._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).export_preview_result._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = config.ExportPreviewResultResponse() + # 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 = config.ExportPreviewResultResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.export_preview_result(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_export_preview_result_rest_unset_required_fields(): + transport = transports.ConfigRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.export_preview_result._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", ))) + + +def test_list_terraform_versions_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 = ConfigClient( + 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_terraform_versions in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_terraform_versions] = mock_rpc + + request = {} + client.list_terraform_versions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_terraform_versions(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_terraform_versions_rest_required_fields(request_type=config.ListTerraformVersionsRequest): + transport_class = transports.ConfigRestTransport + + 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 + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_terraform_versions._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_terraform_versions._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("filter", "order_by", "page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = config.ListTerraformVersionsResponse() + # 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 = config.ListTerraformVersionsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_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_terraform_versions(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_terraform_versions_rest_unset_required_fields(): + transport = transports.ConfigRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_terraform_versions._get_unset_required_fields({}) + assert set(unset_fields) == (set(("filter", "orderBy", "pageSize", "pageToken", )) & set(("parent", ))) + + +def test_list_terraform_versions_rest_flattened(): + client = ConfigClient( + 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 = config.ListTerraformVersionsResponse() + + # 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 = config.ListTerraformVersionsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_terraform_versions(**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/*}/terraformVersions" % client.transport._host, args[1]) + + +def test_list_terraform_versions_rest_flattened_error(transport: str = 'rest'): + client = ConfigClient( + 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_terraform_versions( + config.ListTerraformVersionsRequest(), + parent='parent_value', + ) + + +def test_list_terraform_versions_rest_pager(transport: str = 'rest'): + client = ConfigClient( + 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 = ( + config.ListTerraformVersionsResponse( + terraform_versions=[ + config.TerraformVersion(), + config.TerraformVersion(), + config.TerraformVersion(), + ], + next_page_token='abc', + ), + config.ListTerraformVersionsResponse( + terraform_versions=[], + next_page_token='def', + ), + config.ListTerraformVersionsResponse( + terraform_versions=[ + config.TerraformVersion(), + ], + next_page_token='ghi', + ), + config.ListTerraformVersionsResponse( + terraform_versions=[ + config.TerraformVersion(), + config.TerraformVersion(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(config.ListTerraformVersionsResponse.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_terraform_versions(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, config.TerraformVersion) + for i in results) + + pages = list(client.list_terraform_versions(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_get_terraform_version_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 = ConfigClient( + 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_terraform_version in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_terraform_version] = mock_rpc + + request = {} + client.get_terraform_version(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_terraform_version(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_terraform_version_rest_required_fields(request_type=config.GetTerraformVersionRequest): + transport_class = transports.ConfigRestTransport + + 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 + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_terraform_version._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_terraform_version._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = config.TerraformVersion() + # 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 = config.TerraformVersion.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_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_terraform_version(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_terraform_version_rest_unset_required_fields(): + transport = transports.ConfigRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_terraform_version._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_terraform_version_rest_flattened(): + client = ConfigClient( + 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 = config.TerraformVersion() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/terraformVersions/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 = config.TerraformVersion.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_terraform_version(**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/*/terraformVersions/*}" % client.transport._host, args[1]) + + +def test_get_terraform_version_rest_flattened_error(transport: str = 'rest'): + client = ConfigClient( + 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_terraform_version( + config.GetTerraformVersionRequest(), + name='name_value', + ) + + +def test_list_resource_changes_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 = ConfigClient( + 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_changes in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_changes] = mock_rpc + + request = {} + client.list_resource_changes(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_resource_changes(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_changes_rest_required_fields(request_type=config.ListResourceChangesRequest): + transport_class = transports.ConfigRestTransport + + 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 + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_resource_changes._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_resource_changes._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("filter", "order_by", "page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = config.ListResourceChangesResponse() + # 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 = config.ListResourceChangesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_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_changes(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_resource_changes_rest_unset_required_fields(): + transport = transports.ConfigRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_resource_changes._get_unset_required_fields({}) + assert set(unset_fields) == (set(("filter", "orderBy", "pageSize", "pageToken", )) & set(("parent", ))) + + +def test_list_resource_changes_rest_flattened(): + client = ConfigClient( + 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 = config.ListResourceChangesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/previews/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 = config.ListResourceChangesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_changes(**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/*/previews/*}/resourceChanges" % client.transport._host, args[1]) + + +def test_list_resource_changes_rest_flattened_error(transport: str = 'rest'): + client = ConfigClient( + 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_changes( + config.ListResourceChangesRequest(), + parent='parent_value', + ) + + +def test_list_resource_changes_rest_pager(transport: str = 'rest'): + client = ConfigClient( + 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 = ( + config.ListResourceChangesResponse( + resource_changes=[ + config.ResourceChange(), + config.ResourceChange(), + config.ResourceChange(), + ], + next_page_token='abc', + ), + config.ListResourceChangesResponse( + resource_changes=[], + next_page_token='def', + ), + config.ListResourceChangesResponse( + resource_changes=[ + config.ResourceChange(), + ], + next_page_token='ghi', + ), + config.ListResourceChangesResponse( + resource_changes=[ + config.ResourceChange(), + config.ResourceChange(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(config.ListResourceChangesResponse.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/previews/sample3'} + + pager = client.list_resource_changes(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, config.ResourceChange) + for i in results) + + pages = list(client.list_resource_changes(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_get_resource_change_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 = ConfigClient( + 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_change in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_change] = mock_rpc + + request = {} + client.get_resource_change(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_resource_change(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_change_rest_required_fields(request_type=config.GetResourceChangeRequest): + transport_class = transports.ConfigRestTransport + + 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 + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_resource_change._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_resource_change._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = config.ResourceChange() + # 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 = config.ResourceChange.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_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_change(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_resource_change_rest_unset_required_fields(): + transport = transports.ConfigRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_resource_change._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_resource_change_rest_flattened(): + client = ConfigClient( + 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 = config.ResourceChange() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/previews/sample3/resourceChanges/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 = config.ResourceChange.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_change(**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/*/previews/*/resourceChanges/*}" % client.transport._host, args[1]) + + +def test_get_resource_change_rest_flattened_error(transport: str = 'rest'): + client = ConfigClient( + 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_change( + config.GetResourceChangeRequest(), + name='name_value', + ) + + +def test_list_resource_drifts_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 = ConfigClient( + 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_drifts in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_drifts] = mock_rpc + + request = {} + client.list_resource_drifts(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_resource_drifts(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_drifts_rest_required_fields(request_type=config.ListResourceDriftsRequest): + transport_class = transports.ConfigRestTransport + + 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 + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_resource_drifts._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_resource_drifts._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("filter", "order_by", "page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = config.ListResourceDriftsResponse() + # 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 = config.ListResourceDriftsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_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_drifts(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_resource_drifts_rest_unset_required_fields(): + transport = transports.ConfigRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_resource_drifts._get_unset_required_fields({}) + assert set(unset_fields) == (set(("filter", "orderBy", "pageSize", "pageToken", )) & set(("parent", ))) + + +def test_list_resource_drifts_rest_flattened(): + client = ConfigClient( + 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 = config.ListResourceDriftsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/previews/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 = config.ListResourceDriftsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_drifts(**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/*/previews/*}/resourceDrifts" % client.transport._host, args[1]) + + +def test_list_resource_drifts_rest_flattened_error(transport: str = 'rest'): + client = ConfigClient( + 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_drifts( + config.ListResourceDriftsRequest(), + parent='parent_value', + ) + + +def test_list_resource_drifts_rest_pager(transport: str = 'rest'): + client = ConfigClient( + 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 = ( + config.ListResourceDriftsResponse( + resource_drifts=[ + config.ResourceDrift(), + config.ResourceDrift(), + config.ResourceDrift(), + ], + next_page_token='abc', + ), + config.ListResourceDriftsResponse( + resource_drifts=[], + next_page_token='def', + ), + config.ListResourceDriftsResponse( + resource_drifts=[ + config.ResourceDrift(), + ], + next_page_token='ghi', + ), + config.ListResourceDriftsResponse( + resource_drifts=[ + config.ResourceDrift(), + config.ResourceDrift(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(config.ListResourceDriftsResponse.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/previews/sample3'} + + pager = client.list_resource_drifts(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, config.ResourceDrift) + for i in results) + + pages = list(client.list_resource_drifts(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_get_resource_drift_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 = ConfigClient( + 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_drift in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = 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_drift] = mock_rpc + + request = {} + client.get_resource_drift(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_resource_drift(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_drift_rest_required_fields(request_type=config.GetResourceDriftRequest): + transport_class = transports.ConfigRestTransport + + 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 + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_resource_drift._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_resource_drift._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = config.ResourceDrift() + # 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 = config.ResourceDrift.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_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_drift(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_resource_drift_rest_unset_required_fields(): + transport = transports.ConfigRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_resource_drift._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_resource_drift_rest_flattened(): + client = ConfigClient( + 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 = config.ResourceDrift() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/previews/sample3/resourceDrifts/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 = config.ResourceDrift.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_drift(**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/*/previews/*/resourceDrifts/*}" % client.transport._host, args[1]) + + +def test_get_resource_drift_rest_flattened_error(transport: str = 'rest'): + client = ConfigClient( + 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_drift( + config.GetResourceDriftRequest(), + name='name_value', + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.ConfigGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.ConfigGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ConfigClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.ConfigGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ConfigClient( + 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 = ConfigClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ConfigGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ConfigClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ConfigGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = ConfigClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.ConfigGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.ConfigGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.ConfigGrpcTransport, + transports.ConfigGrpcAsyncIOTransport, + transports.ConfigRestTransport, +]) +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 = ConfigClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = ConfigClient( + 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_deployments_empty_call_grpc(): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_deployments), + '__call__') as call: + call.return_value = config.ListDeploymentsResponse() + client.list_deployments(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = config.ListDeploymentsRequest() + + assert args[0] == request_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_deployment_empty_call_grpc(): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_deployment), + '__call__') as call: + call.return_value = config.Deployment() + client.get_deployment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = config.GetDeploymentRequest() + + assert args[0] == request_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_deployment_empty_call_grpc(): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_deployment), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_deployment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = config.CreateDeploymentRequest() + + assert args[0] == request_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_deployment_empty_call_grpc(): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_deployment), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.update_deployment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = config.UpdateDeploymentRequest() + + assert args[0] == request_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_deployment_empty_call_grpc(): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_deployment), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_deployment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = config.DeleteDeploymentRequest() + + assert args[0] == request_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_revisions_empty_call_grpc(): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_revisions), + '__call__') as call: + call.return_value = config.ListRevisionsResponse() + client.list_revisions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = config.ListRevisionsRequest() + + assert args[0] == request_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_revision_empty_call_grpc(): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_revision), + '__call__') as call: + call.return_value = config.Revision() + client.get_revision(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = config.GetRevisionRequest() + + assert args[0] == request_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_empty_call_grpc(): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_resource), + '__call__') as call: + call.return_value = config.Resource() + client.get_resource(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = config.GetResourceRequest() + + assert args[0] == request_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_resources_empty_call_grpc(): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_resources), + '__call__') as call: + call.return_value = config.ListResourcesResponse() + client.list_resources(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = config.ListResourcesRequest() + + assert args[0] == request_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_export_deployment_statefile_empty_call_grpc(): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.export_deployment_statefile), + '__call__') as call: + call.return_value = config.Statefile() + client.export_deployment_statefile(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = config.ExportDeploymentStatefileRequest() + + assert args[0] == request_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_export_revision_statefile_empty_call_grpc(): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.export_revision_statefile), + '__call__') as call: + call.return_value = config.Statefile() + client.export_revision_statefile(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = config.ExportRevisionStatefileRequest() + + assert args[0] == request_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_import_statefile_empty_call_grpc(): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.import_statefile), + '__call__') as call: + call.return_value = config.Statefile() + client.import_statefile(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = config.ImportStatefileRequest() + + assert args[0] == request_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_statefile_empty_call_grpc(): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_statefile), + '__call__') as call: + call.return_value = None + client.delete_statefile(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = config.DeleteStatefileRequest() + + assert args[0] == request_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_lock_deployment_empty_call_grpc(): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.lock_deployment), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.lock_deployment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = config.LockDeploymentRequest() + + assert args[0] == request_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_unlock_deployment_empty_call_grpc(): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.unlock_deployment), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.unlock_deployment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = config.UnlockDeploymentRequest() + + assert args[0] == request_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_export_lock_info_empty_call_grpc(): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.export_lock_info), + '__call__') as call: + call.return_value = config.LockInfo() + client.export_lock_info(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = config.ExportLockInfoRequest() + + assert args[0] == request_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_preview_empty_call_grpc(): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_preview), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_preview(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = config.CreatePreviewRequest() + + assert args[0] == request_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_preview_empty_call_grpc(): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_preview), + '__call__') as call: + call.return_value = config.Preview() + client.get_preview(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = config.GetPreviewRequest() + + assert args[0] == request_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_previews_empty_call_grpc(): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_previews), + '__call__') as call: + call.return_value = config.ListPreviewsResponse() + client.list_previews(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = config.ListPreviewsRequest() + + assert args[0] == request_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_preview_empty_call_grpc(): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_preview), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_preview(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = config.DeletePreviewRequest() + + assert args[0] == request_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_export_preview_result_empty_call_grpc(): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.export_preview_result), + '__call__') as call: + call.return_value = config.ExportPreviewResultResponse() + client.export_preview_result(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = config.ExportPreviewResultRequest() + + assert args[0] == request_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_terraform_versions_empty_call_grpc(): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_terraform_versions), + '__call__') as call: + call.return_value = config.ListTerraformVersionsResponse() + client.list_terraform_versions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = config.ListTerraformVersionsRequest() + + assert args[0] == request_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_terraform_version_empty_call_grpc(): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_terraform_version), + '__call__') as call: + call.return_value = config.TerraformVersion() + client.get_terraform_version(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = config.GetTerraformVersionRequest() + + assert args[0] == request_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_changes_empty_call_grpc(): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_resource_changes), + '__call__') as call: + call.return_value = config.ListResourceChangesResponse() + client.list_resource_changes(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = config.ListResourceChangesRequest() + + assert args[0] == request_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_change_empty_call_grpc(): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_resource_change), + '__call__') as call: + call.return_value = config.ResourceChange() + client.get_resource_change(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = config.GetResourceChangeRequest() + + assert args[0] == request_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_drifts_empty_call_grpc(): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_resource_drifts), + '__call__') as call: + call.return_value = config.ListResourceDriftsResponse() + client.list_resource_drifts(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = config.ListResourceDriftsRequest() + + assert args[0] == request_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_drift_empty_call_grpc(): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_resource_drift), + '__call__') as call: + call.return_value = config.ResourceDrift() + client.get_resource_drift(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = config.GetResourceDriftRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = ConfigAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = ConfigAsyncClient( + 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_deployments_empty_call_grpc_asyncio(): + client = ConfigAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_deployments), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.ListDeploymentsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + await client.list_deployments(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = config.ListDeploymentsRequest() + + assert args[0] == request_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_deployment_empty_call_grpc_asyncio(): + client = ConfigAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_deployment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.Deployment( + name='name_value', + state=config.Deployment.State.CREATING, + latest_revision='latest_revision_value', + state_detail='state_detail_value', + error_code=config.Deployment.ErrorCode.REVISION_FAILED, + delete_build='delete_build_value', + delete_logs='delete_logs_value', + error_logs='error_logs_value', + artifacts_gcs_bucket='artifacts_gcs_bucket_value', + service_account='service_account_value', + import_existing_resources=True, + worker_pool='worker_pool_value', + lock_state=config.Deployment.LockState.LOCKED, + tf_version_constraint='tf_version_constraint_value', + tf_version='tf_version_value', + quota_validation=config.QuotaValidation.ENABLED, + )) + await client.get_deployment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = config.GetDeploymentRequest() + + assert args[0] == request_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_deployment_empty_call_grpc_asyncio(): + client = ConfigAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_deployment), + '__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_deployment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = config.CreateDeploymentRequest() + + assert args[0] == request_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_deployment_empty_call_grpc_asyncio(): + client = ConfigAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_deployment), + '__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_deployment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = config.UpdateDeploymentRequest() + + assert args[0] == request_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_deployment_empty_call_grpc_asyncio(): + client = ConfigAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_deployment), + '__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_deployment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = config.DeleteDeploymentRequest() + + assert args[0] == request_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_revisions_empty_call_grpc_asyncio(): + client = ConfigAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_revisions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.ListRevisionsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + await client.list_revisions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = config.ListRevisionsRequest() + + assert args[0] == request_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_revision_empty_call_grpc_asyncio(): + client = ConfigAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_revision), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.Revision( + name='name_value', + action=config.Revision.Action.CREATE, + state=config.Revision.State.APPLYING, + state_detail='state_detail_value', + error_code=config.Revision.ErrorCode.CLOUD_BUILD_PERMISSION_DENIED, + build='build_value', + logs='logs_value', + error_logs='error_logs_value', + service_account='service_account_value', + import_existing_resources=True, + worker_pool='worker_pool_value', + tf_version_constraint='tf_version_constraint_value', + tf_version='tf_version_value', + quota_validation_results='quota_validation_results_value', + quota_validation=config.QuotaValidation.ENABLED, + )) + await client.get_revision(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = config.GetRevisionRequest() + + assert args[0] == request_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_empty_call_grpc_asyncio(): + client = ConfigAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_resource), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.Resource( + name='name_value', + intent=config.Resource.Intent.CREATE, + state=config.Resource.State.PLANNED, + )) + await client.get_resource(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = config.GetResourceRequest() + + assert args[0] == request_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_resources_empty_call_grpc_asyncio(): + client = ConfigAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_resources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.ListResourcesResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + await client.list_resources(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = config.ListResourcesRequest() + + assert args[0] == request_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_export_deployment_statefile_empty_call_grpc_asyncio(): + client = ConfigAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.export_deployment_statefile), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.Statefile( + signed_uri='signed_uri_value', + )) + await client.export_deployment_statefile(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = config.ExportDeploymentStatefileRequest() + + assert args[0] == request_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_export_revision_statefile_empty_call_grpc_asyncio(): + client = ConfigAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.export_revision_statefile), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.Statefile( + signed_uri='signed_uri_value', + )) + await client.export_revision_statefile(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = config.ExportRevisionStatefileRequest() + + assert args[0] == request_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_import_statefile_empty_call_grpc_asyncio(): + client = ConfigAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.import_statefile), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.Statefile( + signed_uri='signed_uri_value', + )) + await client.import_statefile(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = config.ImportStatefileRequest() + + assert args[0] == request_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_statefile_empty_call_grpc_asyncio(): + client = ConfigAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_statefile), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_statefile(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = config.DeleteStatefileRequest() + + assert args[0] == request_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_lock_deployment_empty_call_grpc_asyncio(): + client = ConfigAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.lock_deployment), + '__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.lock_deployment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = config.LockDeploymentRequest() + + assert args[0] == request_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_unlock_deployment_empty_call_grpc_asyncio(): + client = ConfigAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.unlock_deployment), + '__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.unlock_deployment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = config.UnlockDeploymentRequest() + + assert args[0] == request_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_export_lock_info_empty_call_grpc_asyncio(): + client = ConfigAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.export_lock_info), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.LockInfo( + lock_id=725, + operation='operation_value', + info='info_value', + who='who_value', + version='version_value', + )) + await client.export_lock_info(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = config.ExportLockInfoRequest() + + assert args[0] == request_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_preview_empty_call_grpc_asyncio(): + client = ConfigAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_preview), + '__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_preview(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = config.CreatePreviewRequest() + + assert args[0] == request_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_preview_empty_call_grpc_asyncio(): + client = ConfigAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_preview), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.Preview( + name='name_value', + state=config.Preview.State.CREATING, + deployment='deployment_value', + preview_mode=config.Preview.PreviewMode.DEFAULT, + service_account='service_account_value', + artifacts_gcs_bucket='artifacts_gcs_bucket_value', + worker_pool='worker_pool_value', + error_code=config.Preview.ErrorCode.CLOUD_BUILD_PERMISSION_DENIED, + build='build_value', + error_logs='error_logs_value', + logs='logs_value', + tf_version='tf_version_value', + tf_version_constraint='tf_version_constraint_value', + )) + await client.get_preview(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = config.GetPreviewRequest() + + assert args[0] == request_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_previews_empty_call_grpc_asyncio(): + client = ConfigAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_previews), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.ListPreviewsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + await client.list_previews(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = config.ListPreviewsRequest() + + assert args[0] == request_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_preview_empty_call_grpc_asyncio(): + client = ConfigAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_preview), + '__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_preview(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = config.DeletePreviewRequest() + + assert args[0] == request_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_export_preview_result_empty_call_grpc_asyncio(): + client = ConfigAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.export_preview_result), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.ExportPreviewResultResponse( + )) + await client.export_preview_result(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = config.ExportPreviewResultRequest() + + assert args[0] == request_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_terraform_versions_empty_call_grpc_asyncio(): + client = ConfigAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_terraform_versions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.ListTerraformVersionsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + await client.list_terraform_versions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = config.ListTerraformVersionsRequest() + + assert args[0] == request_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_terraform_version_empty_call_grpc_asyncio(): + client = ConfigAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_terraform_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.TerraformVersion( + name='name_value', + state=config.TerraformVersion.State.ACTIVE, + )) + await client.get_terraform_version(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = config.GetTerraformVersionRequest() + + assert args[0] == request_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_changes_empty_call_grpc_asyncio(): + client = ConfigAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_resource_changes), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.ListResourceChangesResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + await client.list_resource_changes(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = config.ListResourceChangesRequest() + + assert args[0] == request_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_change_empty_call_grpc_asyncio(): + client = ConfigAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_resource_change), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.ResourceChange( + name='name_value', + intent=config.ResourceChange.Intent.CREATE, + )) + await client.get_resource_change(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = config.GetResourceChangeRequest() + + assert args[0] == request_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_drifts_empty_call_grpc_asyncio(): + client = ConfigAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_resource_drifts), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.ListResourceDriftsResponse( + next_page_token='next_page_token_value', + unreachable=['unreachable_value'], + )) + await client.list_resource_drifts(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = config.ListResourceDriftsRequest() + + assert args[0] == request_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_drift_empty_call_grpc_asyncio(): + client = ConfigAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_resource_drift), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.ResourceDrift( + name='name_value', + )) + await client.get_resource_drift(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = config.GetResourceDriftRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = ConfigClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_list_deployments_rest_bad_request(request_type=config.ListDeploymentsRequest): + client = ConfigClient( + 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_deployments(request) + + +@pytest.mark.parametrize("request_type", [ + config.ListDeploymentsRequest, + dict, +]) +def test_list_deployments_rest_call_success(request_type): + client = ConfigClient( + 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 = config.ListDeploymentsResponse( + 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 = config.ListDeploymentsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_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_deployments(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDeploymentsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_deployments_rest_interceptors(null_interceptor): + transport = transports.ConfigRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ConfigRestInterceptor(), + ) + client = ConfigClient(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.ConfigRestInterceptor, "post_list_deployments") as post, \ + mock.patch.object(transports.ConfigRestInterceptor, "post_list_deployments_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.ConfigRestInterceptor, "pre_list_deployments") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = config.ListDeploymentsRequest.pb(config.ListDeploymentsRequest()) + 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 = config.ListDeploymentsResponse.to_json(config.ListDeploymentsResponse()) + req.return_value.content = return_value + + request = config.ListDeploymentsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = config.ListDeploymentsResponse() + post_with_metadata.return_value = config.ListDeploymentsResponse(), metadata + + client.list_deployments(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_deployment_rest_bad_request(request_type=config.GetDeploymentRequest): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/deployments/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_deployment(request) + + +@pytest.mark.parametrize("request_type", [ + config.GetDeploymentRequest, + dict, +]) +def test_get_deployment_rest_call_success(request_type): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/deployments/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 = config.Deployment( + name='name_value', + state=config.Deployment.State.CREATING, + latest_revision='latest_revision_value', + state_detail='state_detail_value', + error_code=config.Deployment.ErrorCode.REVISION_FAILED, + delete_build='delete_build_value', + delete_logs='delete_logs_value', + error_logs='error_logs_value', + artifacts_gcs_bucket='artifacts_gcs_bucket_value', + service_account='service_account_value', + import_existing_resources=True, + worker_pool='worker_pool_value', + lock_state=config.Deployment.LockState.LOCKED, + tf_version_constraint='tf_version_constraint_value', + tf_version='tf_version_value', + quota_validation=config.QuotaValidation.ENABLED, + ) + + # 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 = config.Deployment.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_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_deployment(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, config.Deployment) + assert response.name == 'name_value' + assert response.state == config.Deployment.State.CREATING + assert response.latest_revision == 'latest_revision_value' + assert response.state_detail == 'state_detail_value' + assert response.error_code == config.Deployment.ErrorCode.REVISION_FAILED + assert response.delete_build == 'delete_build_value' + assert response.delete_logs == 'delete_logs_value' + assert response.error_logs == 'error_logs_value' + assert response.artifacts_gcs_bucket == 'artifacts_gcs_bucket_value' + assert response.service_account == 'service_account_value' + assert response.import_existing_resources is True + assert response.worker_pool == 'worker_pool_value' + assert response.lock_state == config.Deployment.LockState.LOCKED + assert response.tf_version_constraint == 'tf_version_constraint_value' + assert response.tf_version == 'tf_version_value' + assert response.quota_validation == config.QuotaValidation.ENABLED + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_deployment_rest_interceptors(null_interceptor): + transport = transports.ConfigRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ConfigRestInterceptor(), + ) + client = ConfigClient(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.ConfigRestInterceptor, "post_get_deployment") as post, \ + mock.patch.object(transports.ConfigRestInterceptor, "post_get_deployment_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.ConfigRestInterceptor, "pre_get_deployment") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = config.GetDeploymentRequest.pb(config.GetDeploymentRequest()) + 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 = config.Deployment.to_json(config.Deployment()) + req.return_value.content = return_value + + request = config.GetDeploymentRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = config.Deployment() + post_with_metadata.return_value = config.Deployment(), metadata + + client.get_deployment(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_create_deployment_rest_bad_request(request_type=config.CreateDeploymentRequest): + client = ConfigClient( + 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_deployment(request) + + +@pytest.mark.parametrize("request_type", [ + config.CreateDeploymentRequest, + dict, +]) +def test_create_deployment_rest_call_success(request_type): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["deployment"] = {'terraform_blueprint': {'gcs_source': 'gcs_source_value', 'git_source': {'repo': 'repo_value', 'directory': 'directory_value', 'ref': 'ref_value'}, 'input_values': {}}, 'name': 'name_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'state': 1, 'latest_revision': 'latest_revision_value', 'state_detail': 'state_detail_value', 'error_code': 1, 'delete_results': {'content': 'content_value', 'artifacts': 'artifacts_value', 'outputs': {}}, 'delete_build': 'delete_build_value', 'delete_logs': 'delete_logs_value', 'tf_errors': [{'resource_address': 'resource_address_value', 'http_response_code': 1928, 'error_description': 'error_description_value', 'error': {'code': 411, 'message': 'message_value', 'details': [{'type_url': 'type.googleapis.com/google.protobuf.Duration', 'value': b'\x08\x0c\x10\xdb\x07'}]}}], 'error_logs': 'error_logs_value', 'artifacts_gcs_bucket': 'artifacts_gcs_bucket_value', 'service_account': 'service_account_value', 'import_existing_resources': True, 'worker_pool': 'worker_pool_value', 'lock_state': 1, 'tf_version_constraint': 'tf_version_constraint_value', 'tf_version': 'tf_version_value', 'quota_validation': 1, 'annotations': {}, 'provider_config': {'source_type': 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 = config.CreateDeploymentRequest.meta.fields["deployment"] + + 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["deployment"].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["deployment"][field])): + del request_init["deployment"][field][i][subfield] + else: + del request_init["deployment"][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_deployment(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_deployment_rest_interceptors(null_interceptor): + transport = transports.ConfigRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ConfigRestInterceptor(), + ) + client = ConfigClient(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.ConfigRestInterceptor, "post_create_deployment") as post, \ + mock.patch.object(transports.ConfigRestInterceptor, "post_create_deployment_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.ConfigRestInterceptor, "pre_create_deployment") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = config.CreateDeploymentRequest.pb(config.CreateDeploymentRequest()) + 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 = config.CreateDeploymentRequest() + 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_deployment(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_deployment_rest_bad_request(request_type=config.UpdateDeploymentRequest): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'deployment': {'name': 'projects/sample1/locations/sample2/deployments/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_deployment(request) + + +@pytest.mark.parametrize("request_type", [ + config.UpdateDeploymentRequest, + dict, +]) +def test_update_deployment_rest_call_success(request_type): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'deployment': {'name': 'projects/sample1/locations/sample2/deployments/sample3'}} + request_init["deployment"] = {'terraform_blueprint': {'gcs_source': 'gcs_source_value', 'git_source': {'repo': 'repo_value', 'directory': 'directory_value', 'ref': 'ref_value'}, 'input_values': {}}, 'name': 'projects/sample1/locations/sample2/deployments/sample3', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'state': 1, 'latest_revision': 'latest_revision_value', 'state_detail': 'state_detail_value', 'error_code': 1, 'delete_results': {'content': 'content_value', 'artifacts': 'artifacts_value', 'outputs': {}}, 'delete_build': 'delete_build_value', 'delete_logs': 'delete_logs_value', 'tf_errors': [{'resource_address': 'resource_address_value', 'http_response_code': 1928, 'error_description': 'error_description_value', 'error': {'code': 411, 'message': 'message_value', 'details': [{'type_url': 'type.googleapis.com/google.protobuf.Duration', 'value': b'\x08\x0c\x10\xdb\x07'}]}}], 'error_logs': 'error_logs_value', 'artifacts_gcs_bucket': 'artifacts_gcs_bucket_value', 'service_account': 'service_account_value', 'import_existing_resources': True, 'worker_pool': 'worker_pool_value', 'lock_state': 1, 'tf_version_constraint': 'tf_version_constraint_value', 'tf_version': 'tf_version_value', 'quota_validation': 1, 'annotations': {}, 'provider_config': {'source_type': 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 = config.UpdateDeploymentRequest.meta.fields["deployment"] + + 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["deployment"].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["deployment"][field])): + del request_init["deployment"][field][i][subfield] + else: + del request_init["deployment"][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_deployment(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_deployment_rest_interceptors(null_interceptor): + transport = transports.ConfigRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ConfigRestInterceptor(), + ) + client = ConfigClient(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.ConfigRestInterceptor, "post_update_deployment") as post, \ + mock.patch.object(transports.ConfigRestInterceptor, "post_update_deployment_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.ConfigRestInterceptor, "pre_update_deployment") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = config.UpdateDeploymentRequest.pb(config.UpdateDeploymentRequest()) + 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 = config.UpdateDeploymentRequest() + 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_deployment(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_deployment_rest_bad_request(request_type=config.DeleteDeploymentRequest): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/deployments/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_deployment(request) + + +@pytest.mark.parametrize("request_type", [ + config.DeleteDeploymentRequest, + dict, +]) +def test_delete_deployment_rest_call_success(request_type): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/deployments/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_deployment(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_deployment_rest_interceptors(null_interceptor): + transport = transports.ConfigRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ConfigRestInterceptor(), + ) + client = ConfigClient(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.ConfigRestInterceptor, "post_delete_deployment") as post, \ + mock.patch.object(transports.ConfigRestInterceptor, "post_delete_deployment_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.ConfigRestInterceptor, "pre_delete_deployment") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = config.DeleteDeploymentRequest.pb(config.DeleteDeploymentRequest()) + 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 = config.DeleteDeploymentRequest() + 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_deployment(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_revisions_rest_bad_request(request_type=config.ListRevisionsRequest): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/deployments/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_revisions(request) + + +@pytest.mark.parametrize("request_type", [ + config.ListRevisionsRequest, + dict, +]) +def test_list_revisions_rest_call_success(request_type): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/deployments/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 = config.ListRevisionsResponse( + 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 = config.ListRevisionsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_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_revisions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListRevisionsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_revisions_rest_interceptors(null_interceptor): + transport = transports.ConfigRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ConfigRestInterceptor(), + ) + client = ConfigClient(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.ConfigRestInterceptor, "post_list_revisions") as post, \ + mock.patch.object(transports.ConfigRestInterceptor, "post_list_revisions_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.ConfigRestInterceptor, "pre_list_revisions") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = config.ListRevisionsRequest.pb(config.ListRevisionsRequest()) + 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 = config.ListRevisionsResponse.to_json(config.ListRevisionsResponse()) + req.return_value.content = return_value + + request = config.ListRevisionsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = config.ListRevisionsResponse() + post_with_metadata.return_value = config.ListRevisionsResponse(), metadata + + client.list_revisions(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_revision_rest_bad_request(request_type=config.GetRevisionRequest): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/deployments/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_revision(request) + + +@pytest.mark.parametrize("request_type", [ + config.GetRevisionRequest, + dict, +]) +def test_get_revision_rest_call_success(request_type): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/deployments/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 = config.Revision( + name='name_value', + action=config.Revision.Action.CREATE, + state=config.Revision.State.APPLYING, + state_detail='state_detail_value', + error_code=config.Revision.ErrorCode.CLOUD_BUILD_PERMISSION_DENIED, + build='build_value', + logs='logs_value', + error_logs='error_logs_value', + service_account='service_account_value', + import_existing_resources=True, + worker_pool='worker_pool_value', + tf_version_constraint='tf_version_constraint_value', + tf_version='tf_version_value', + quota_validation_results='quota_validation_results_value', + quota_validation=config.QuotaValidation.ENABLED, + ) + + # 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 = config.Revision.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_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_revision(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, config.Revision) + assert response.name == 'name_value' + assert response.action == config.Revision.Action.CREATE + assert response.state == config.Revision.State.APPLYING + assert response.state_detail == 'state_detail_value' + assert response.error_code == config.Revision.ErrorCode.CLOUD_BUILD_PERMISSION_DENIED + assert response.build == 'build_value' + assert response.logs == 'logs_value' + assert response.error_logs == 'error_logs_value' + assert response.service_account == 'service_account_value' + assert response.import_existing_resources is True + assert response.worker_pool == 'worker_pool_value' + assert response.tf_version_constraint == 'tf_version_constraint_value' + assert response.tf_version == 'tf_version_value' + assert response.quota_validation_results == 'quota_validation_results_value' + assert response.quota_validation == config.QuotaValidation.ENABLED + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_revision_rest_interceptors(null_interceptor): + transport = transports.ConfigRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ConfigRestInterceptor(), + ) + client = ConfigClient(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.ConfigRestInterceptor, "post_get_revision") as post, \ + mock.patch.object(transports.ConfigRestInterceptor, "post_get_revision_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.ConfigRestInterceptor, "pre_get_revision") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = config.GetRevisionRequest.pb(config.GetRevisionRequest()) + 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 = config.Revision.to_json(config.Revision()) + req.return_value.content = return_value + + request = config.GetRevisionRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = config.Revision() + post_with_metadata.return_value = config.Revision(), metadata + + client.get_revision(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_resource_rest_bad_request(request_type=config.GetResourceRequest): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/deployments/sample3/revisions/sample4/resources/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_resource(request) + + +@pytest.mark.parametrize("request_type", [ + config.GetResourceRequest, + dict, +]) +def test_get_resource_rest_call_success(request_type): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/deployments/sample3/revisions/sample4/resources/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 = config.Resource( + name='name_value', + intent=config.Resource.Intent.CREATE, + state=config.Resource.State.PLANNED, + ) + + # 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 = config.Resource.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_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(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, config.Resource) + assert response.name == 'name_value' + assert response.intent == config.Resource.Intent.CREATE + assert response.state == config.Resource.State.PLANNED + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_resource_rest_interceptors(null_interceptor): + transport = transports.ConfigRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ConfigRestInterceptor(), + ) + client = ConfigClient(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.ConfigRestInterceptor, "post_get_resource") as post, \ + mock.patch.object(transports.ConfigRestInterceptor, "post_get_resource_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.ConfigRestInterceptor, "pre_get_resource") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = config.GetResourceRequest.pb(config.GetResourceRequest()) + 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 = config.Resource.to_json(config.Resource()) + req.return_value.content = return_value + + request = config.GetResourceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = config.Resource() + post_with_metadata.return_value = config.Resource(), metadata + + client.get_resource(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_resources_rest_bad_request(request_type=config.ListResourcesRequest): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/deployments/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.list_resources(request) + + +@pytest.mark.parametrize("request_type", [ + config.ListResourcesRequest, + dict, +]) +def test_list_resources_rest_call_success(request_type): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/deployments/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 = config.ListResourcesResponse( + 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 = config.ListResourcesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_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_resources(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListResourcesPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_resources_rest_interceptors(null_interceptor): + transport = transports.ConfigRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ConfigRestInterceptor(), + ) + client = ConfigClient(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.ConfigRestInterceptor, "post_list_resources") as post, \ + mock.patch.object(transports.ConfigRestInterceptor, "post_list_resources_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.ConfigRestInterceptor, "pre_list_resources") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = config.ListResourcesRequest.pb(config.ListResourcesRequest()) + 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 = config.ListResourcesResponse.to_json(config.ListResourcesResponse()) + req.return_value.content = return_value + + request = config.ListResourcesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = config.ListResourcesResponse() + post_with_metadata.return_value = config.ListResourcesResponse(), metadata + + client.list_resources(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_export_deployment_statefile_rest_bad_request(request_type=config.ExportDeploymentStatefileRequest): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/deployments/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.export_deployment_statefile(request) + + +@pytest.mark.parametrize("request_type", [ + config.ExportDeploymentStatefileRequest, + dict, +]) +def test_export_deployment_statefile_rest_call_success(request_type): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/deployments/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 = config.Statefile( + signed_uri='signed_uri_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 = config.Statefile.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.export_deployment_statefile(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, config.Statefile) + assert response.signed_uri == 'signed_uri_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_export_deployment_statefile_rest_interceptors(null_interceptor): + transport = transports.ConfigRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ConfigRestInterceptor(), + ) + client = ConfigClient(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.ConfigRestInterceptor, "post_export_deployment_statefile") as post, \ + mock.patch.object(transports.ConfigRestInterceptor, "post_export_deployment_statefile_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.ConfigRestInterceptor, "pre_export_deployment_statefile") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = config.ExportDeploymentStatefileRequest.pb(config.ExportDeploymentStatefileRequest()) + 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 = config.Statefile.to_json(config.Statefile()) + req.return_value.content = return_value + + request = config.ExportDeploymentStatefileRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = config.Statefile() + post_with_metadata.return_value = config.Statefile(), metadata + + client.export_deployment_statefile(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_export_revision_statefile_rest_bad_request(request_type=config.ExportRevisionStatefileRequest): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/deployments/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.export_revision_statefile(request) + + +@pytest.mark.parametrize("request_type", [ + config.ExportRevisionStatefileRequest, + dict, +]) +def test_export_revision_statefile_rest_call_success(request_type): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/deployments/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 = config.Statefile( + signed_uri='signed_uri_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 = config.Statefile.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.export_revision_statefile(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, config.Statefile) + assert response.signed_uri == 'signed_uri_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_export_revision_statefile_rest_interceptors(null_interceptor): + transport = transports.ConfigRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ConfigRestInterceptor(), + ) + client = ConfigClient(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.ConfigRestInterceptor, "post_export_revision_statefile") as post, \ + mock.patch.object(transports.ConfigRestInterceptor, "post_export_revision_statefile_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.ConfigRestInterceptor, "pre_export_revision_statefile") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = config.ExportRevisionStatefileRequest.pb(config.ExportRevisionStatefileRequest()) + 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 = config.Statefile.to_json(config.Statefile()) + req.return_value.content = return_value + + request = config.ExportRevisionStatefileRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = config.Statefile() + post_with_metadata.return_value = config.Statefile(), metadata + + client.export_revision_statefile(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_import_statefile_rest_bad_request(request_type=config.ImportStatefileRequest): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/deployments/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.import_statefile(request) + + +@pytest.mark.parametrize("request_type", [ + config.ImportStatefileRequest, + dict, +]) +def test_import_statefile_rest_call_success(request_type): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/deployments/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 = config.Statefile( + signed_uri='signed_uri_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 = config.Statefile.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.import_statefile(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, config.Statefile) + assert response.signed_uri == 'signed_uri_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_import_statefile_rest_interceptors(null_interceptor): + transport = transports.ConfigRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ConfigRestInterceptor(), + ) + client = ConfigClient(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.ConfigRestInterceptor, "post_import_statefile") as post, \ + mock.patch.object(transports.ConfigRestInterceptor, "post_import_statefile_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.ConfigRestInterceptor, "pre_import_statefile") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = config.ImportStatefileRequest.pb(config.ImportStatefileRequest()) + 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 = config.Statefile.to_json(config.Statefile()) + req.return_value.content = return_value + + request = config.ImportStatefileRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = config.Statefile() + post_with_metadata.return_value = config.Statefile(), metadata + + client.import_statefile(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_statefile_rest_bad_request(request_type=config.DeleteStatefileRequest): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/deployments/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_statefile(request) + + +@pytest.mark.parametrize("request_type", [ + config.DeleteStatefileRequest, + dict, +]) +def test_delete_statefile_rest_call_success(request_type): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/deployments/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 + + # 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_statefile(request) + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_statefile_rest_interceptors(null_interceptor): + transport = transports.ConfigRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ConfigRestInterceptor(), + ) + client = ConfigClient(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.ConfigRestInterceptor, "pre_delete_statefile") as pre: + pre.assert_not_called() + pb_message = config.DeleteStatefileRequest.pb(config.DeleteStatefileRequest()) + 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"} + + request = config.DeleteStatefileRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_statefile(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_lock_deployment_rest_bad_request(request_type=config.LockDeploymentRequest): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/deployments/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.lock_deployment(request) + + +@pytest.mark.parametrize("request_type", [ + config.LockDeploymentRequest, + dict, +]) +def test_lock_deployment_rest_call_success(request_type): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/deployments/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.lock_deployment(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_lock_deployment_rest_interceptors(null_interceptor): + transport = transports.ConfigRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ConfigRestInterceptor(), + ) + client = ConfigClient(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.ConfigRestInterceptor, "post_lock_deployment") as post, \ + mock.patch.object(transports.ConfigRestInterceptor, "post_lock_deployment_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.ConfigRestInterceptor, "pre_lock_deployment") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = config.LockDeploymentRequest.pb(config.LockDeploymentRequest()) + 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 = config.LockDeploymentRequest() + 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.lock_deployment(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_unlock_deployment_rest_bad_request(request_type=config.UnlockDeploymentRequest): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/deployments/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.unlock_deployment(request) + + +@pytest.mark.parametrize("request_type", [ + config.UnlockDeploymentRequest, + dict, +]) +def test_unlock_deployment_rest_call_success(request_type): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/deployments/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.unlock_deployment(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_unlock_deployment_rest_interceptors(null_interceptor): + transport = transports.ConfigRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ConfigRestInterceptor(), + ) + client = ConfigClient(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.ConfigRestInterceptor, "post_unlock_deployment") as post, \ + mock.patch.object(transports.ConfigRestInterceptor, "post_unlock_deployment_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.ConfigRestInterceptor, "pre_unlock_deployment") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = config.UnlockDeploymentRequest.pb(config.UnlockDeploymentRequest()) + 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 = config.UnlockDeploymentRequest() + 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.unlock_deployment(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_export_lock_info_rest_bad_request(request_type=config.ExportLockInfoRequest): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/deployments/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.export_lock_info(request) + + +@pytest.mark.parametrize("request_type", [ + config.ExportLockInfoRequest, + dict, +]) +def test_export_lock_info_rest_call_success(request_type): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/deployments/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 = config.LockInfo( + lock_id=725, + operation='operation_value', + info='info_value', + who='who_value', + version='version_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 = config.LockInfo.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.export_lock_info(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, config.LockInfo) + assert response.lock_id == 725 + assert response.operation == 'operation_value' + assert response.info == 'info_value' + assert response.who == 'who_value' + assert response.version == 'version_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_export_lock_info_rest_interceptors(null_interceptor): + transport = transports.ConfigRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ConfigRestInterceptor(), + ) + client = ConfigClient(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.ConfigRestInterceptor, "post_export_lock_info") as post, \ + mock.patch.object(transports.ConfigRestInterceptor, "post_export_lock_info_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.ConfigRestInterceptor, "pre_export_lock_info") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = config.ExportLockInfoRequest.pb(config.ExportLockInfoRequest()) + 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 = config.LockInfo.to_json(config.LockInfo()) + req.return_value.content = return_value + + request = config.ExportLockInfoRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = config.LockInfo() + post_with_metadata.return_value = config.LockInfo(), metadata + + client.export_lock_info(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_create_preview_rest_bad_request(request_type=config.CreatePreviewRequest): + client = ConfigClient( + 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_preview(request) + + +@pytest.mark.parametrize("request_type", [ + config.CreatePreviewRequest, + dict, +]) +def test_create_preview_rest_call_success(request_type): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["preview"] = {'terraform_blueprint': {'gcs_source': 'gcs_source_value', 'git_source': {'repo': 'repo_value', 'directory': 'directory_value', 'ref': 'ref_value'}, 'input_values': {}}, 'name': 'name_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'labels': {}, 'state': 1, 'deployment': 'deployment_value', 'preview_mode': 1, 'service_account': 'service_account_value', 'artifacts_gcs_bucket': 'artifacts_gcs_bucket_value', 'worker_pool': 'worker_pool_value', 'error_code': 1, 'error_status': {'code': 411, 'message': 'message_value', 'details': [{'type_url': 'type.googleapis.com/google.protobuf.Duration', 'value': b'\x08\x0c\x10\xdb\x07'}]}, 'build': 'build_value', 'tf_errors': [{'resource_address': 'resource_address_value', 'http_response_code': 1928, 'error_description': 'error_description_value', 'error': {}}], 'error_logs': 'error_logs_value', 'preview_artifacts': {'content': 'content_value', 'artifacts': 'artifacts_value'}, 'logs': 'logs_value', 'tf_version': 'tf_version_value', 'tf_version_constraint': 'tf_version_constraint_value', 'annotations': {}, 'provider_config': {'source_type': 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 = config.CreatePreviewRequest.meta.fields["preview"] + + 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["preview"].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["preview"][field])): + del request_init["preview"][field][i][subfield] + else: + del request_init["preview"][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_preview(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_preview_rest_interceptors(null_interceptor): + transport = transports.ConfigRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ConfigRestInterceptor(), + ) + client = ConfigClient(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.ConfigRestInterceptor, "post_create_preview") as post, \ + mock.patch.object(transports.ConfigRestInterceptor, "post_create_preview_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.ConfigRestInterceptor, "pre_create_preview") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = config.CreatePreviewRequest.pb(config.CreatePreviewRequest()) + 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 = config.CreatePreviewRequest() + 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_preview(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_preview_rest_bad_request(request_type=config.GetPreviewRequest): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/previews/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_preview(request) + + +@pytest.mark.parametrize("request_type", [ + config.GetPreviewRequest, + dict, +]) +def test_get_preview_rest_call_success(request_type): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/previews/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 = config.Preview( + name='name_value', + state=config.Preview.State.CREATING, + deployment='deployment_value', + preview_mode=config.Preview.PreviewMode.DEFAULT, + service_account='service_account_value', + artifacts_gcs_bucket='artifacts_gcs_bucket_value', + worker_pool='worker_pool_value', + error_code=config.Preview.ErrorCode.CLOUD_BUILD_PERMISSION_DENIED, + build='build_value', + error_logs='error_logs_value', + logs='logs_value', + tf_version='tf_version_value', + tf_version_constraint='tf_version_constraint_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 = config.Preview.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_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_preview(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, config.Preview) + assert response.name == 'name_value' + assert response.state == config.Preview.State.CREATING + assert response.deployment == 'deployment_value' + assert response.preview_mode == config.Preview.PreviewMode.DEFAULT + assert response.service_account == 'service_account_value' + assert response.artifacts_gcs_bucket == 'artifacts_gcs_bucket_value' + assert response.worker_pool == 'worker_pool_value' + assert response.error_code == config.Preview.ErrorCode.CLOUD_BUILD_PERMISSION_DENIED + assert response.build == 'build_value' + assert response.error_logs == 'error_logs_value' + assert response.logs == 'logs_value' + assert response.tf_version == 'tf_version_value' + assert response.tf_version_constraint == 'tf_version_constraint_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_preview_rest_interceptors(null_interceptor): + transport = transports.ConfigRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ConfigRestInterceptor(), + ) + client = ConfigClient(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.ConfigRestInterceptor, "post_get_preview") as post, \ + mock.patch.object(transports.ConfigRestInterceptor, "post_get_preview_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.ConfigRestInterceptor, "pre_get_preview") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = config.GetPreviewRequest.pb(config.GetPreviewRequest()) + 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 = config.Preview.to_json(config.Preview()) + req.return_value.content = return_value + + request = config.GetPreviewRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = config.Preview() + post_with_metadata.return_value = config.Preview(), metadata + + client.get_preview(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_previews_rest_bad_request(request_type=config.ListPreviewsRequest): + client = ConfigClient( + 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_previews(request) + + +@pytest.mark.parametrize("request_type", [ + config.ListPreviewsRequest, + dict, +]) +def test_list_previews_rest_call_success(request_type): + client = ConfigClient( + 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 = config.ListPreviewsResponse( + 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 = config.ListPreviewsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_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_previews(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListPreviewsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_previews_rest_interceptors(null_interceptor): + transport = transports.ConfigRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ConfigRestInterceptor(), + ) + client = ConfigClient(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.ConfigRestInterceptor, "post_list_previews") as post, \ + mock.patch.object(transports.ConfigRestInterceptor, "post_list_previews_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.ConfigRestInterceptor, "pre_list_previews") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = config.ListPreviewsRequest.pb(config.ListPreviewsRequest()) + 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 = config.ListPreviewsResponse.to_json(config.ListPreviewsResponse()) + req.return_value.content = return_value + + request = config.ListPreviewsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = config.ListPreviewsResponse() + post_with_metadata.return_value = config.ListPreviewsResponse(), metadata + + client.list_previews(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_preview_rest_bad_request(request_type=config.DeletePreviewRequest): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/previews/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_preview(request) + + +@pytest.mark.parametrize("request_type", [ + config.DeletePreviewRequest, + dict, +]) +def test_delete_preview_rest_call_success(request_type): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/previews/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_preview(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_preview_rest_interceptors(null_interceptor): + transport = transports.ConfigRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ConfigRestInterceptor(), + ) + client = ConfigClient(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.ConfigRestInterceptor, "post_delete_preview") as post, \ + mock.patch.object(transports.ConfigRestInterceptor, "post_delete_preview_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.ConfigRestInterceptor, "pre_delete_preview") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = config.DeletePreviewRequest.pb(config.DeletePreviewRequest()) + 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 = config.DeletePreviewRequest() + 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_preview(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_export_preview_result_rest_bad_request(request_type=config.ExportPreviewResultRequest): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/previews/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.export_preview_result(request) + + +@pytest.mark.parametrize("request_type", [ + config.ExportPreviewResultRequest, + dict, +]) +def test_export_preview_result_rest_call_success(request_type): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/previews/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 = config.ExportPreviewResultResponse( + ) + + # 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 = config.ExportPreviewResultResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.export_preview_result(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, config.ExportPreviewResultResponse) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_export_preview_result_rest_interceptors(null_interceptor): + transport = transports.ConfigRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ConfigRestInterceptor(), + ) + client = ConfigClient(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.ConfigRestInterceptor, "post_export_preview_result") as post, \ + mock.patch.object(transports.ConfigRestInterceptor, "post_export_preview_result_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.ConfigRestInterceptor, "pre_export_preview_result") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = config.ExportPreviewResultRequest.pb(config.ExportPreviewResultRequest()) + 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 = config.ExportPreviewResultResponse.to_json(config.ExportPreviewResultResponse()) + req.return_value.content = return_value + + request = config.ExportPreviewResultRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = config.ExportPreviewResultResponse() + post_with_metadata.return_value = config.ExportPreviewResultResponse(), metadata + + client.export_preview_result(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_terraform_versions_rest_bad_request(request_type=config.ListTerraformVersionsRequest): + client = ConfigClient( + 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_terraform_versions(request) + + +@pytest.mark.parametrize("request_type", [ + config.ListTerraformVersionsRequest, + dict, +]) +def test_list_terraform_versions_rest_call_success(request_type): + client = ConfigClient( + 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 = config.ListTerraformVersionsResponse( + 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 = config.ListTerraformVersionsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_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_terraform_versions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListTerraformVersionsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_terraform_versions_rest_interceptors(null_interceptor): + transport = transports.ConfigRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ConfigRestInterceptor(), + ) + client = ConfigClient(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.ConfigRestInterceptor, "post_list_terraform_versions") as post, \ + mock.patch.object(transports.ConfigRestInterceptor, "post_list_terraform_versions_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.ConfigRestInterceptor, "pre_list_terraform_versions") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = config.ListTerraformVersionsRequest.pb(config.ListTerraformVersionsRequest()) + 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 = config.ListTerraformVersionsResponse.to_json(config.ListTerraformVersionsResponse()) + req.return_value.content = return_value + + request = config.ListTerraformVersionsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = config.ListTerraformVersionsResponse() + post_with_metadata.return_value = config.ListTerraformVersionsResponse(), metadata + + client.list_terraform_versions(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_terraform_version_rest_bad_request(request_type=config.GetTerraformVersionRequest): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/terraformVersions/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_terraform_version(request) + + +@pytest.mark.parametrize("request_type", [ + config.GetTerraformVersionRequest, + dict, +]) +def test_get_terraform_version_rest_call_success(request_type): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/terraformVersions/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 = config.TerraformVersion( + name='name_value', + state=config.TerraformVersion.State.ACTIVE, + ) + + # 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 = config.TerraformVersion.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_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_terraform_version(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, config.TerraformVersion) + assert response.name == 'name_value' + assert response.state == config.TerraformVersion.State.ACTIVE + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_terraform_version_rest_interceptors(null_interceptor): + transport = transports.ConfigRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ConfigRestInterceptor(), + ) + client = ConfigClient(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.ConfigRestInterceptor, "post_get_terraform_version") as post, \ + mock.patch.object(transports.ConfigRestInterceptor, "post_get_terraform_version_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.ConfigRestInterceptor, "pre_get_terraform_version") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = config.GetTerraformVersionRequest.pb(config.GetTerraformVersionRequest()) + 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 = config.TerraformVersion.to_json(config.TerraformVersion()) + req.return_value.content = return_value + + request = config.GetTerraformVersionRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = config.TerraformVersion() + post_with_metadata.return_value = config.TerraformVersion(), metadata + + client.get_terraform_version(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_resource_changes_rest_bad_request(request_type=config.ListResourceChangesRequest): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/previews/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_resource_changes(request) + + +@pytest.mark.parametrize("request_type", [ + config.ListResourceChangesRequest, + dict, +]) +def test_list_resource_changes_rest_call_success(request_type): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/previews/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 = config.ListResourceChangesResponse( + 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 = config.ListResourceChangesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_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_changes(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListResourceChangesPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_resource_changes_rest_interceptors(null_interceptor): + transport = transports.ConfigRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ConfigRestInterceptor(), + ) + client = ConfigClient(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.ConfigRestInterceptor, "post_list_resource_changes") as post, \ + mock.patch.object(transports.ConfigRestInterceptor, "post_list_resource_changes_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.ConfigRestInterceptor, "pre_list_resource_changes") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = config.ListResourceChangesRequest.pb(config.ListResourceChangesRequest()) + 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 = config.ListResourceChangesResponse.to_json(config.ListResourceChangesResponse()) + req.return_value.content = return_value + + request = config.ListResourceChangesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = config.ListResourceChangesResponse() + post_with_metadata.return_value = config.ListResourceChangesResponse(), metadata + + client.list_resource_changes(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_resource_change_rest_bad_request(request_type=config.GetResourceChangeRequest): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/previews/sample3/resourceChanges/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_resource_change(request) + + +@pytest.mark.parametrize("request_type", [ + config.GetResourceChangeRequest, + dict, +]) +def test_get_resource_change_rest_call_success(request_type): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/previews/sample3/resourceChanges/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 = config.ResourceChange( + name='name_value', + intent=config.ResourceChange.Intent.CREATE, + ) + + # 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 = config.ResourceChange.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_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_change(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, config.ResourceChange) + assert response.name == 'name_value' + assert response.intent == config.ResourceChange.Intent.CREATE + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_resource_change_rest_interceptors(null_interceptor): + transport = transports.ConfigRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ConfigRestInterceptor(), + ) + client = ConfigClient(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.ConfigRestInterceptor, "post_get_resource_change") as post, \ + mock.patch.object(transports.ConfigRestInterceptor, "post_get_resource_change_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.ConfigRestInterceptor, "pre_get_resource_change") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = config.GetResourceChangeRequest.pb(config.GetResourceChangeRequest()) + 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 = config.ResourceChange.to_json(config.ResourceChange()) + req.return_value.content = return_value + + request = config.GetResourceChangeRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = config.ResourceChange() + post_with_metadata.return_value = config.ResourceChange(), metadata + + client.get_resource_change(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_resource_drifts_rest_bad_request(request_type=config.ListResourceDriftsRequest): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/previews/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_resource_drifts(request) + + +@pytest.mark.parametrize("request_type", [ + config.ListResourceDriftsRequest, + dict, +]) +def test_list_resource_drifts_rest_call_success(request_type): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/previews/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 = config.ListResourceDriftsResponse( + 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 = config.ListResourceDriftsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_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_drifts(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListResourceDriftsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.unreachable == ['unreachable_value'] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_resource_drifts_rest_interceptors(null_interceptor): + transport = transports.ConfigRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ConfigRestInterceptor(), + ) + client = ConfigClient(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.ConfigRestInterceptor, "post_list_resource_drifts") as post, \ + mock.patch.object(transports.ConfigRestInterceptor, "post_list_resource_drifts_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.ConfigRestInterceptor, "pre_list_resource_drifts") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = config.ListResourceDriftsRequest.pb(config.ListResourceDriftsRequest()) + 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 = config.ListResourceDriftsResponse.to_json(config.ListResourceDriftsResponse()) + req.return_value.content = return_value + + request = config.ListResourceDriftsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = config.ListResourceDriftsResponse() + post_with_metadata.return_value = config.ListResourceDriftsResponse(), metadata + + client.list_resource_drifts(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_resource_drift_rest_bad_request(request_type=config.GetResourceDriftRequest): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/previews/sample3/resourceDrifts/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_resource_drift(request) + + +@pytest.mark.parametrize("request_type", [ + config.GetResourceDriftRequest, + dict, +]) +def test_get_resource_drift_rest_call_success(request_type): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/previews/sample3/resourceDrifts/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 = config.ResourceDrift( + 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 = config.ResourceDrift.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_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_drift(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, config.ResourceDrift) + assert response.name == 'name_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_resource_drift_rest_interceptors(null_interceptor): + transport = transports.ConfigRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ConfigRestInterceptor(), + ) + client = ConfigClient(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.ConfigRestInterceptor, "post_get_resource_drift") as post, \ + mock.patch.object(transports.ConfigRestInterceptor, "post_get_resource_drift_with_metadata") as post_with_metadata, \ + mock.patch.object(transports.ConfigRestInterceptor, "pre_get_resource_drift") as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = config.GetResourceDriftRequest.pb(config.GetResourceDriftRequest()) + 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 = config.ResourceDrift.to_json(config.ResourceDrift()) + req.return_value.content = return_value + + request = config.GetResourceDriftRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = config.ResourceDrift() + post_with_metadata.return_value = config.ResourceDrift(), metadata + + client.get_resource_drift(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 = ConfigClient( + 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 = ConfigClient( + 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 = ConfigClient( + 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 = ConfigClient( + 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 = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/deployments/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 = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'resource': 'projects/sample1/locations/sample2/deployments/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 = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/deployments/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 = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'resource': 'projects/sample1/locations/sample2/deployments/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 = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/deployments/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 = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'resource': 'projects/sample1/locations/sample2/deployments/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 = ConfigClient( + 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 = ConfigClient( + 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 = ConfigClient( + 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 = ConfigClient( + 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 = ConfigClient( + 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 = ConfigClient( + 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 = ConfigClient( + 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 = ConfigClient( + 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 = ConfigClient( + 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_deployments_empty_call_rest(): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_deployments), + '__call__') as call: + client.list_deployments(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = config.ListDeploymentsRequest() + + assert args[0] == request_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_deployment_empty_call_rest(): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_deployment), + '__call__') as call: + client.get_deployment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = config.GetDeploymentRequest() + + assert args[0] == request_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_deployment_empty_call_rest(): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_deployment), + '__call__') as call: + client.create_deployment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = config.CreateDeploymentRequest() + + assert args[0] == request_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_deployment_empty_call_rest(): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_deployment), + '__call__') as call: + client.update_deployment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = config.UpdateDeploymentRequest() + + assert args[0] == request_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_deployment_empty_call_rest(): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_deployment), + '__call__') as call: + client.delete_deployment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = config.DeleteDeploymentRequest() + + assert args[0] == request_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_revisions_empty_call_rest(): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_revisions), + '__call__') as call: + client.list_revisions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = config.ListRevisionsRequest() + + assert args[0] == request_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_revision_empty_call_rest(): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_revision), + '__call__') as call: + client.get_revision(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = config.GetRevisionRequest() + + assert args[0] == request_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_empty_call_rest(): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_resource), + '__call__') as call: + client.get_resource(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = config.GetResourceRequest() + + assert args[0] == request_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_resources_empty_call_rest(): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_resources), + '__call__') as call: + client.list_resources(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = config.ListResourcesRequest() + + assert args[0] == request_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_export_deployment_statefile_empty_call_rest(): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.export_deployment_statefile), + '__call__') as call: + client.export_deployment_statefile(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = config.ExportDeploymentStatefileRequest() + + assert args[0] == request_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_export_revision_statefile_empty_call_rest(): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.export_revision_statefile), + '__call__') as call: + client.export_revision_statefile(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = config.ExportRevisionStatefileRequest() + + assert args[0] == request_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_import_statefile_empty_call_rest(): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.import_statefile), + '__call__') as call: + client.import_statefile(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = config.ImportStatefileRequest() + + assert args[0] == request_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_statefile_empty_call_rest(): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_statefile), + '__call__') as call: + client.delete_statefile(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = config.DeleteStatefileRequest() + + assert args[0] == request_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_lock_deployment_empty_call_rest(): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.lock_deployment), + '__call__') as call: + client.lock_deployment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = config.LockDeploymentRequest() + + assert args[0] == request_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_unlock_deployment_empty_call_rest(): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.unlock_deployment), + '__call__') as call: + client.unlock_deployment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = config.UnlockDeploymentRequest() + + assert args[0] == request_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_export_lock_info_empty_call_rest(): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.export_lock_info), + '__call__') as call: + client.export_lock_info(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = config.ExportLockInfoRequest() + + assert args[0] == request_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_preview_empty_call_rest(): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_preview), + '__call__') as call: + client.create_preview(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = config.CreatePreviewRequest() + + assert args[0] == request_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_preview_empty_call_rest(): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_preview), + '__call__') as call: + client.get_preview(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = config.GetPreviewRequest() + + assert args[0] == request_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_previews_empty_call_rest(): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_previews), + '__call__') as call: + client.list_previews(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = config.ListPreviewsRequest() + + assert args[0] == request_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_preview_empty_call_rest(): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_preview), + '__call__') as call: + client.delete_preview(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = config.DeletePreviewRequest() + + assert args[0] == request_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_export_preview_result_empty_call_rest(): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.export_preview_result), + '__call__') as call: + client.export_preview_result(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = config.ExportPreviewResultRequest() + + assert args[0] == request_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_terraform_versions_empty_call_rest(): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_terraform_versions), + '__call__') as call: + client.list_terraform_versions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = config.ListTerraformVersionsRequest() + + assert args[0] == request_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_terraform_version_empty_call_rest(): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_terraform_version), + '__call__') as call: + client.get_terraform_version(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = config.GetTerraformVersionRequest() + + assert args[0] == request_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_changes_empty_call_rest(): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_resource_changes), + '__call__') as call: + client.list_resource_changes(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = config.ListResourceChangesRequest() + + assert args[0] == request_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_change_empty_call_rest(): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_resource_change), + '__call__') as call: + client.get_resource_change(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = config.GetResourceChangeRequest() + + assert args[0] == request_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_drifts_empty_call_rest(): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_resource_drifts), + '__call__') as call: + client.list_resource_drifts(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = config.ListResourceDriftsRequest() + + assert args[0] == request_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_drift_empty_call_rest(): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_resource_drift), + '__call__') as call: + client.get_resource_drift(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = config.GetResourceDriftRequest() + + assert args[0] == request_msg + + +def test_config_rest_lro_client(): + client = ConfigClient( + 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 = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.ConfigGrpcTransport, + ) + +def test_config_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.ConfigTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_config_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.config_v1.services.config.transports.ConfigTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.ConfigTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_deployments', + 'get_deployment', + 'create_deployment', + 'update_deployment', + 'delete_deployment', + 'list_revisions', + 'get_revision', + 'get_resource', + 'list_resources', + 'export_deployment_statefile', + 'export_revision_statefile', + 'import_statefile', + 'delete_statefile', + 'lock_deployment', + 'unlock_deployment', + 'export_lock_info', + 'create_preview', + 'get_preview', + 'list_previews', + 'delete_preview', + 'export_preview_result', + 'list_terraform_versions', + 'get_terraform_version', + 'list_resource_changes', + 'get_resource_change', + 'list_resource_drifts', + 'get_resource_drift', + '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_config_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.config_v1.services.config.transports.ConfigTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ConfigTransport( + 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_config_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.config_v1.services.config.transports.ConfigTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ConfigTransport() + adc.assert_called_once() + + +def test_config_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) + ConfigClient() + 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.ConfigGrpcTransport, + transports.ConfigGrpcAsyncIOTransport, + ], +) +def test_config_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.ConfigGrpcTransport, + transports.ConfigGrpcAsyncIOTransport, + transports.ConfigRestTransport, + ], +) +def test_config_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.ConfigGrpcTransport, grpc_helpers), + (transports.ConfigGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_config_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( + "config.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="config.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.ConfigGrpcTransport, transports.ConfigGrpcAsyncIOTransport]) +def test_config_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_config_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.ConfigRestTransport ( + 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_config_host_no_port(transport_name): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='config.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'config.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://config.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_config_host_with_port(transport_name): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='config.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'config.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://config.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_config_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = ConfigClient( + credentials=creds1, + transport=transport_name, + ) + client2 = ConfigClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.list_deployments._session + session2 = client2.transport.list_deployments._session + assert session1 != session2 + session1 = client1.transport.get_deployment._session + session2 = client2.transport.get_deployment._session + assert session1 != session2 + session1 = client1.transport.create_deployment._session + session2 = client2.transport.create_deployment._session + assert session1 != session2 + session1 = client1.transport.update_deployment._session + session2 = client2.transport.update_deployment._session + assert session1 != session2 + session1 = client1.transport.delete_deployment._session + session2 = client2.transport.delete_deployment._session + assert session1 != session2 + session1 = client1.transport.list_revisions._session + session2 = client2.transport.list_revisions._session + assert session1 != session2 + session1 = client1.transport.get_revision._session + session2 = client2.transport.get_revision._session + assert session1 != session2 + session1 = client1.transport.get_resource._session + session2 = client2.transport.get_resource._session + assert session1 != session2 + session1 = client1.transport.list_resources._session + session2 = client2.transport.list_resources._session + assert session1 != session2 + session1 = client1.transport.export_deployment_statefile._session + session2 = client2.transport.export_deployment_statefile._session + assert session1 != session2 + session1 = client1.transport.export_revision_statefile._session + session2 = client2.transport.export_revision_statefile._session + assert session1 != session2 + session1 = client1.transport.import_statefile._session + session2 = client2.transport.import_statefile._session + assert session1 != session2 + session1 = client1.transport.delete_statefile._session + session2 = client2.transport.delete_statefile._session + assert session1 != session2 + session1 = client1.transport.lock_deployment._session + session2 = client2.transport.lock_deployment._session + assert session1 != session2 + session1 = client1.transport.unlock_deployment._session + session2 = client2.transport.unlock_deployment._session + assert session1 != session2 + session1 = client1.transport.export_lock_info._session + session2 = client2.transport.export_lock_info._session + assert session1 != session2 + session1 = client1.transport.create_preview._session + session2 = client2.transport.create_preview._session + assert session1 != session2 + session1 = client1.transport.get_preview._session + session2 = client2.transport.get_preview._session + assert session1 != session2 + session1 = client1.transport.list_previews._session + session2 = client2.transport.list_previews._session + assert session1 != session2 + session1 = client1.transport.delete_preview._session + session2 = client2.transport.delete_preview._session + assert session1 != session2 + session1 = client1.transport.export_preview_result._session + session2 = client2.transport.export_preview_result._session + assert session1 != session2 + session1 = client1.transport.list_terraform_versions._session + session2 = client2.transport.list_terraform_versions._session + assert session1 != session2 + session1 = client1.transport.get_terraform_version._session + session2 = client2.transport.get_terraform_version._session + assert session1 != session2 + session1 = client1.transport.list_resource_changes._session + session2 = client2.transport.list_resource_changes._session + assert session1 != session2 + session1 = client1.transport.get_resource_change._session + session2 = client2.transport.get_resource_change._session + assert session1 != session2 + session1 = client1.transport.list_resource_drifts._session + session2 = client2.transport.list_resource_drifts._session + assert session1 != session2 + session1 = client1.transport.get_resource_drift._session + session2 = client2.transport.get_resource_drift._session + assert session1 != session2 +def test_config_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ConfigGrpcTransport( + 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_config_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ConfigGrpcAsyncIOTransport( + 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.parametrize("transport_class", [transports.ConfigGrpcTransport, transports.ConfigGrpcAsyncIOTransport]) +def test_config_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.ConfigGrpcTransport, transports.ConfigGrpcAsyncIOTransport]) +def test_config_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_config_grpc_lro_client(): + client = ConfigClient( + 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_config_grpc_lro_async_client(): + client = ConfigAsyncClient( + 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_deployment_path(): + project = "squid" + location = "clam" + deployment = "whelk" + expected = "projects/{project}/locations/{location}/deployments/{deployment}".format(project=project, location=location, deployment=deployment, ) + actual = ConfigClient.deployment_path(project, location, deployment) + assert expected == actual + + +def test_parse_deployment_path(): + expected = { + "project": "octopus", + "location": "oyster", + "deployment": "nudibranch", + } + path = ConfigClient.deployment_path(**expected) + + # Check that the path construction is reversible. + actual = ConfigClient.parse_deployment_path(path) + assert expected == actual + +def test_preview_path(): + project = "cuttlefish" + location = "mussel" + preview = "winkle" + expected = "projects/{project}/locations/{location}/previews/{preview}".format(project=project, location=location, preview=preview, ) + actual = ConfigClient.preview_path(project, location, preview) + assert expected == actual + + +def test_parse_preview_path(): + expected = { + "project": "nautilus", + "location": "scallop", + "preview": "abalone", + } + path = ConfigClient.preview_path(**expected) + + # Check that the path construction is reversible. + actual = ConfigClient.parse_preview_path(path) + assert expected == actual + +def test_resource_path(): + project = "squid" + location = "clam" + deployment = "whelk" + revision = "octopus" + resource = "oyster" + expected = "projects/{project}/locations/{location}/deployments/{deployment}/revisions/{revision}/resources/{resource}".format(project=project, location=location, deployment=deployment, revision=revision, resource=resource, ) + actual = ConfigClient.resource_path(project, location, deployment, revision, resource) + assert expected == actual + + +def test_parse_resource_path(): + expected = { + "project": "nudibranch", + "location": "cuttlefish", + "deployment": "mussel", + "revision": "winkle", + "resource": "nautilus", + } + path = ConfigClient.resource_path(**expected) + + # Check that the path construction is reversible. + actual = ConfigClient.parse_resource_path(path) + assert expected == actual + +def test_resource_change_path(): + project = "scallop" + location = "abalone" + preview = "squid" + resource_change = "clam" + expected = "projects/{project}/locations/{location}/previews/{preview}/resourceChanges/{resource_change}".format(project=project, location=location, preview=preview, resource_change=resource_change, ) + actual = ConfigClient.resource_change_path(project, location, preview, resource_change) + assert expected == actual + + +def test_parse_resource_change_path(): + expected = { + "project": "whelk", + "location": "octopus", + "preview": "oyster", + "resource_change": "nudibranch", + } + path = ConfigClient.resource_change_path(**expected) + + # Check that the path construction is reversible. + actual = ConfigClient.parse_resource_change_path(path) + assert expected == actual + +def test_resource_drift_path(): + project = "cuttlefish" + location = "mussel" + preview = "winkle" + resource_drift = "nautilus" + expected = "projects/{project}/locations/{location}/previews/{preview}/resourceDrifts/{resource_drift}".format(project=project, location=location, preview=preview, resource_drift=resource_drift, ) + actual = ConfigClient.resource_drift_path(project, location, preview, resource_drift) + assert expected == actual + + +def test_parse_resource_drift_path(): + expected = { + "project": "scallop", + "location": "abalone", + "preview": "squid", + "resource_drift": "clam", + } + path = ConfigClient.resource_drift_path(**expected) + + # Check that the path construction is reversible. + actual = ConfigClient.parse_resource_drift_path(path) + assert expected == actual + +def test_revision_path(): + project = "whelk" + location = "octopus" + deployment = "oyster" + revision = "nudibranch" + expected = "projects/{project}/locations/{location}/deployments/{deployment}/revisions/{revision}".format(project=project, location=location, deployment=deployment, revision=revision, ) + actual = ConfigClient.revision_path(project, location, deployment, revision) + assert expected == actual + + +def test_parse_revision_path(): + expected = { + "project": "cuttlefish", + "location": "mussel", + "deployment": "winkle", + "revision": "nautilus", + } + path = ConfigClient.revision_path(**expected) + + # Check that the path construction is reversible. + actual = ConfigClient.parse_revision_path(path) + assert expected == actual + +def test_service_account_path(): + project = "scallop" + service_account = "abalone" + expected = "projects/{project}/serviceAccounts/{service_account}".format(project=project, service_account=service_account, ) + actual = ConfigClient.service_account_path(project, service_account) + assert expected == actual + + +def test_parse_service_account_path(): + expected = { + "project": "squid", + "service_account": "clam", + } + path = ConfigClient.service_account_path(**expected) + + # Check that the path construction is reversible. + actual = ConfigClient.parse_service_account_path(path) + assert expected == actual + +def test_terraform_version_path(): + project = "whelk" + location = "octopus" + terraform_version = "oyster" + expected = "projects/{project}/locations/{location}/terraformVersions/{terraform_version}".format(project=project, location=location, terraform_version=terraform_version, ) + actual = ConfigClient.terraform_version_path(project, location, terraform_version) + assert expected == actual + + +def test_parse_terraform_version_path(): + expected = { + "project": "nudibranch", + "location": "cuttlefish", + "terraform_version": "mussel", + } + path = ConfigClient.terraform_version_path(**expected) + + # Check that the path construction is reversible. + actual = ConfigClient.parse_terraform_version_path(path) + assert expected == actual + +def test_worker_pool_path(): + project = "winkle" + location = "nautilus" + worker_pool = "scallop" + expected = "projects/{project}/locations/{location}/workerPools/{worker_pool}".format(project=project, location=location, worker_pool=worker_pool, ) + actual = ConfigClient.worker_pool_path(project, location, worker_pool) + assert expected == actual + + +def test_parse_worker_pool_path(): + expected = { + "project": "abalone", + "location": "squid", + "worker_pool": "clam", + } + path = ConfigClient.worker_pool_path(**expected) + + # Check that the path construction is reversible. + actual = ConfigClient.parse_worker_pool_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "whelk" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = ConfigClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "octopus", + } + path = ConfigClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = ConfigClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "oyster" + expected = "folders/{folder}".format(folder=folder, ) + actual = ConfigClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + path = ConfigClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = ConfigClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "cuttlefish" + expected = "organizations/{organization}".format(organization=organization, ) + actual = ConfigClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + path = ConfigClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = ConfigClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "winkle" + expected = "projects/{project}".format(project=project, ) + actual = ConfigClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + path = ConfigClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = ConfigClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "scallop" + location = "abalone" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = ConfigClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = ConfigClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = ConfigClient.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.ConfigTransport, '_prep_wrapped_messages') as prep: + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.ConfigTransport, '_prep_wrapped_messages') as prep: + transport_class = ConfigClient.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 = ConfigClient( + 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 = ConfigAsyncClient( + 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 = ConfigClient( + 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 = ConfigAsyncClient( + 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 = ConfigClient( + 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 = ConfigAsyncClient( + 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_cancel_operation(transport: str = "grpc"): + client = ConfigClient( + 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 = ConfigAsyncClient( + 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 = ConfigClient( + 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 = ConfigAsyncClient( + 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 = ConfigClient( + 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 = ConfigAsyncClient( + 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_get_operation(transport: str = "grpc"): + client = ConfigClient( + 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 = ConfigAsyncClient( + 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 = ConfigClient( + 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 = ConfigAsyncClient( + 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 = ConfigClient( + 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 = ConfigAsyncClient( + 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_list_operations(transport: str = "grpc"): + client = ConfigClient( + 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 = ConfigAsyncClient( + 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 = ConfigClient( + 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 = ConfigAsyncClient( + 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 = ConfigClient( + 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 = ConfigAsyncClient( + 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_locations(transport: str = "grpc"): + client = ConfigClient( + 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 = ConfigAsyncClient( + 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 = ConfigClient( + 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 = ConfigAsyncClient( + 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 = ConfigClient( + 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 = ConfigAsyncClient( + 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_get_location(transport: str = "grpc"): + client = ConfigClient( + 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 = ConfigAsyncClient( + 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 = ConfigClient( + 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 = ConfigAsyncClient( + 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 = ConfigClient( + 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 = ConfigAsyncClient( + 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_set_iam_policy(transport: str = "grpc"): + client = ConfigClient( + 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 = ConfigAsyncClient( + 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 = ConfigClient( + 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 = ConfigAsyncClient( + 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 = ConfigClient( + 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 = ConfigAsyncClient( + 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_get_iam_policy(transport: str = "grpc"): + client = ConfigClient( + 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 = ConfigAsyncClient( + 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 = ConfigClient( + 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 = ConfigAsyncClient( + 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 = ConfigClient( + 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 = ConfigAsyncClient( + 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_test_iam_permissions(transport: str = "grpc"): + client = ConfigClient( + 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 = ConfigAsyncClient( + 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 = ConfigClient( + 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 = ConfigAsyncClient( + 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 = ConfigClient( + 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 = ConfigAsyncClient( + 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_transport_close_grpc(): + client = ConfigClient( + 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 = ConfigAsyncClient( + 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 = ConfigClient( + 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 = ConfigClient( + 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", [ + (ConfigClient, transports.ConfigGrpcTransport), + (ConfigAsyncClient, transports.ConfigGrpcAsyncIOTransport), +]) +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, + ) From 37283ea45123dfed0e76fc4bd697b91632bfe225 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Wed, 3 Sep 2025 00:04:27 +0000 Subject: [PATCH 2/2] =?UTF-8?q?=F0=9F=A6=89=20Updates=20from=20OwlBot=20po?= =?UTF-8?q?st-processor?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md --- .../google-cloud-config/v1/.coveragerc | 13 - .../google-cloud-config/v1/.flake8 | 34 - .../google-cloud-config/v1/LICENSE | 202 - .../google-cloud-config/v1/MANIFEST.in | 20 - .../google-cloud-config/v1/README.rst | 143 - .../v1/docs/_static/custom.css | 20 - .../v1/docs/_templates/layout.html | 50 - .../google-cloud-config/v1/docs/conf.py | 385 - .../v1/docs/config_v1/config.rst | 10 - .../v1/docs/config_v1/services_.rst | 6 - .../v1/docs/config_v1/types_.rst | 6 - .../google-cloud-config/v1/docs/index.rst | 10 - .../v1/docs/multiprocessing.rst | 7 - .../v1/google/cloud/config/__init__.py | 153 - .../v1/google/cloud/config/gapic_version.py | 16 - .../v1/google/cloud/config/py.typed | 2 - .../v1/google/cloud/config_v1/__init__.py | 154 - .../cloud/config_v1/gapic_metadata.json | 433 - .../google/cloud/config_v1/gapic_version.py | 16 - .../v1/google/cloud/config_v1/py.typed | 2 - .../cloud/config_v1/services/__init__.py | 15 - .../config_v1/services/config/__init__.py | 22 - .../config_v1/services/config/async_client.py | 4004 --- .../cloud/config_v1/services/config/client.py | 4436 --- .../cloud/config_v1/services/config/pagers.py | 1000 - .../services/config/transports/README.rst | 9 - .../services/config/transports/__init__.py | 38 - .../services/config/transports/base.py | 661 - .../services/config/transports/grpc.py | 1246 - .../config/transports/grpc_asyncio.py | 1442 - .../services/config/transports/rest.py | 6103 ---- .../services/config/transports/rest_base.py | 1435 - .../google/cloud/config_v1/types/__init__.py | 146 - .../v1/google/cloud/config_v1/types/config.py | 3309 --- .../google-cloud-config/v1/mypy.ini | 3 - .../google-cloud-config/v1/noxfile.py | 591 - ...enerated_config_create_deployment_async.py | 61 - ...generated_config_create_deployment_sync.py | 61 - ...1_generated_config_create_preview_async.py | 61 - ...v1_generated_config_create_preview_sync.py | 61 - ...enerated_config_delete_deployment_async.py | 56 - ...generated_config_delete_deployment_sync.py | 56 - ...1_generated_config_delete_preview_async.py | 56 - ...v1_generated_config_delete_preview_sync.py | 56 - ...generated_config_delete_statefile_async.py | 51 - ..._generated_config_delete_statefile_sync.py | 51 - ...onfig_export_deployment_statefile_async.py | 52 - ...config_export_deployment_statefile_sync.py | 52 - ...generated_config_export_lock_info_async.py | 52 - ..._generated_config_export_lock_info_sync.py | 52 - ...ated_config_export_preview_result_async.py | 52 - ...rated_config_export_preview_result_sync.py | 52 - ..._config_export_revision_statefile_async.py | 52 - ...d_config_export_revision_statefile_sync.py | 52 - ...1_generated_config_get_deployment_async.py | 52 - ...v1_generated_config_get_deployment_sync.py | 52 - ...g_v1_generated_config_get_preview_async.py | 52 - ...ig_v1_generated_config_get_preview_sync.py | 52 - ..._v1_generated_config_get_resource_async.py | 52 - ...erated_config_get_resource_change_async.py | 52 - ...nerated_config_get_resource_change_sync.py | 52 - ...nerated_config_get_resource_drift_async.py | 52 - ...enerated_config_get_resource_drift_sync.py | 52 - ...g_v1_generated_config_get_resource_sync.py | 52 - ..._v1_generated_config_get_revision_async.py | 52 - ...g_v1_generated_config_get_revision_sync.py | 52 - ...ated_config_get_terraform_version_async.py | 52 - ...rated_config_get_terraform_version_sync.py | 52 - ...generated_config_import_statefile_async.py | 53 - ..._generated_config_import_statefile_sync.py | 53 - ...generated_config_list_deployments_async.py | 53 - ..._generated_config_list_deployments_sync.py | 53 - ...v1_generated_config_list_previews_async.py | 53 - ..._v1_generated_config_list_previews_sync.py | 53 - ...ated_config_list_resource_changes_async.py | 53 - ...rated_config_list_resource_changes_sync.py | 53 - ...rated_config_list_resource_drifts_async.py | 53 - ...erated_config_list_resource_drifts_sync.py | 53 - ...1_generated_config_list_resources_async.py | 53 - ...v1_generated_config_list_resources_sync.py | 53 - ...1_generated_config_list_revisions_async.py | 53 - ...v1_generated_config_list_revisions_sync.py | 53 - ...ed_config_list_terraform_versions_async.py | 53 - ...ted_config_list_terraform_versions_sync.py | 53 - ..._generated_config_lock_deployment_async.py | 56 - ...1_generated_config_lock_deployment_sync.py | 56 - ...enerated_config_unlock_deployment_async.py | 57 - ...generated_config_unlock_deployment_sync.py | 57 - ...enerated_config_update_deployment_async.py | 59 - ...generated_config_update_deployment_sync.py | 59 - ...ippet_metadata_google.cloud.config.v1.json | 4380 --- .../v1/scripts/fixup_config_v1_keywords.py | 202 - .../google-cloud-config/v1/setup.py | 99 - .../v1/testing/constraints-3.10.txt | 7 - .../v1/testing/constraints-3.11.txt | 7 - .../v1/testing/constraints-3.12.txt | 7 - .../v1/testing/constraints-3.13.txt | 12 - .../v1/testing/constraints-3.7.txt | 11 - .../v1/testing/constraints-3.8.txt | 7 - .../v1/testing/constraints-3.9.txt | 7 - .../google-cloud-config/v1/tests/__init__.py | 16 - .../v1/tests/unit/__init__.py | 16 - .../v1/tests/unit/gapic/__init__.py | 16 - .../v1/tests/unit/gapic/config_v1/__init__.py | 16 - .../tests/unit/gapic/config_v1/test_config.py | 23350 ---------------- .../google/cloud/config/__init__.py | 2 + .../google/cloud/config_v1/__init__.py | 2 + .../config_v1/services/config/async_client.py | 1 - .../cloud/config_v1/services/config/client.py | 1 - .../google/cloud/config_v1/types/__init__.py | 2 + .../google/cloud/config_v1/types/config.py | 59 + .../tests/unit/gapic/config_v1/test_config.py | 4 +- 112 files changed, 68 insertions(+), 57204 deletions(-) delete mode 100644 owl-bot-staging/google-cloud-config/v1/.coveragerc delete mode 100644 owl-bot-staging/google-cloud-config/v1/.flake8 delete mode 100644 owl-bot-staging/google-cloud-config/v1/LICENSE delete mode 100644 owl-bot-staging/google-cloud-config/v1/MANIFEST.in delete mode 100644 owl-bot-staging/google-cloud-config/v1/README.rst delete mode 100644 owl-bot-staging/google-cloud-config/v1/docs/_static/custom.css delete mode 100644 owl-bot-staging/google-cloud-config/v1/docs/_templates/layout.html delete mode 100644 owl-bot-staging/google-cloud-config/v1/docs/conf.py delete mode 100644 owl-bot-staging/google-cloud-config/v1/docs/config_v1/config.rst delete mode 100644 owl-bot-staging/google-cloud-config/v1/docs/config_v1/services_.rst delete mode 100644 owl-bot-staging/google-cloud-config/v1/docs/config_v1/types_.rst delete mode 100644 owl-bot-staging/google-cloud-config/v1/docs/index.rst delete mode 100644 owl-bot-staging/google-cloud-config/v1/docs/multiprocessing.rst delete mode 100644 owl-bot-staging/google-cloud-config/v1/google/cloud/config/__init__.py delete mode 100644 owl-bot-staging/google-cloud-config/v1/google/cloud/config/gapic_version.py delete mode 100644 owl-bot-staging/google-cloud-config/v1/google/cloud/config/py.typed delete mode 100644 owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/__init__.py delete mode 100644 owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/gapic_metadata.json delete mode 100644 owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/gapic_version.py delete mode 100644 owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/py.typed delete mode 100644 owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/__init__.py delete mode 100644 owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/__init__.py delete mode 100644 owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/async_client.py delete mode 100644 owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/client.py delete mode 100644 owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/pagers.py delete mode 100644 owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/transports/README.rst delete mode 100644 owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/transports/__init__.py delete mode 100644 owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/transports/base.py delete mode 100644 owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/transports/grpc.py delete mode 100644 owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/transports/rest.py delete mode 100644 owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/transports/rest_base.py delete mode 100644 owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/types/__init__.py delete mode 100644 owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/types/config.py delete mode 100644 owl-bot-staging/google-cloud-config/v1/mypy.ini delete mode 100644 owl-bot-staging/google-cloud-config/v1/noxfile.py delete mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_create_deployment_async.py delete mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_create_deployment_sync.py delete mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_create_preview_async.py delete mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_create_preview_sync.py delete mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_delete_deployment_async.py delete mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_delete_deployment_sync.py delete mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_delete_preview_async.py delete mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_delete_preview_sync.py delete mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_delete_statefile_async.py delete mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_delete_statefile_sync.py delete mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_export_deployment_statefile_async.py delete mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_export_deployment_statefile_sync.py delete mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_export_lock_info_async.py delete mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_export_lock_info_sync.py delete mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_export_preview_result_async.py delete mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_export_preview_result_sync.py delete mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_export_revision_statefile_async.py delete mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_export_revision_statefile_sync.py delete mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_deployment_async.py delete mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_deployment_sync.py delete mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_preview_async.py delete mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_preview_sync.py delete mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_resource_async.py delete mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_resource_change_async.py delete mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_resource_change_sync.py delete mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_resource_drift_async.py delete mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_resource_drift_sync.py delete mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_resource_sync.py delete mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_revision_async.py delete mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_revision_sync.py delete mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_terraform_version_async.py delete mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_terraform_version_sync.py delete mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_import_statefile_async.py delete mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_import_statefile_sync.py delete mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_deployments_async.py delete mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_deployments_sync.py delete mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_previews_async.py delete mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_previews_sync.py delete mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_resource_changes_async.py delete mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_resource_changes_sync.py delete mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_resource_drifts_async.py delete mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_resource_drifts_sync.py delete mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_resources_async.py delete mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_resources_sync.py delete mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_revisions_async.py delete mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_revisions_sync.py delete mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_terraform_versions_async.py delete mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_terraform_versions_sync.py delete mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_lock_deployment_async.py delete mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_lock_deployment_sync.py delete mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_unlock_deployment_async.py delete mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_unlock_deployment_sync.py delete mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_update_deployment_async.py delete mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_update_deployment_sync.py delete mode 100644 owl-bot-staging/google-cloud-config/v1/samples/generated_samples/snippet_metadata_google.cloud.config.v1.json delete mode 100644 owl-bot-staging/google-cloud-config/v1/scripts/fixup_config_v1_keywords.py delete mode 100644 owl-bot-staging/google-cloud-config/v1/setup.py delete mode 100644 owl-bot-staging/google-cloud-config/v1/testing/constraints-3.10.txt delete mode 100644 owl-bot-staging/google-cloud-config/v1/testing/constraints-3.11.txt delete mode 100644 owl-bot-staging/google-cloud-config/v1/testing/constraints-3.12.txt delete mode 100644 owl-bot-staging/google-cloud-config/v1/testing/constraints-3.13.txt delete mode 100644 owl-bot-staging/google-cloud-config/v1/testing/constraints-3.7.txt delete mode 100644 owl-bot-staging/google-cloud-config/v1/testing/constraints-3.8.txt delete mode 100644 owl-bot-staging/google-cloud-config/v1/testing/constraints-3.9.txt delete mode 100644 owl-bot-staging/google-cloud-config/v1/tests/__init__.py delete mode 100644 owl-bot-staging/google-cloud-config/v1/tests/unit/__init__.py delete mode 100644 owl-bot-staging/google-cloud-config/v1/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/google-cloud-config/v1/tests/unit/gapic/config_v1/__init__.py delete mode 100644 owl-bot-staging/google-cloud-config/v1/tests/unit/gapic/config_v1/test_config.py diff --git a/owl-bot-staging/google-cloud-config/v1/.coveragerc b/owl-bot-staging/google-cloud-config/v1/.coveragerc deleted file mode 100644 index 01f0878da1cf..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/.coveragerc +++ /dev/null @@ -1,13 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/cloud/config/__init__.py - google/cloud/config/gapic_version.py -exclude_lines = - # Re-enable the standard pragma - pragma: NO COVER - # Ignore debug-only repr - def __repr__ diff --git a/owl-bot-staging/google-cloud-config/v1/.flake8 b/owl-bot-staging/google-cloud-config/v1/.flake8 deleted file mode 100644 index 90316de21489..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/.flake8 +++ /dev/null @@ -1,34 +0,0 @@ -# -*- 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. -# -[flake8] -# TODO(https://github.com/googleapis/gapic-generator-python/issues/2333): -# Resolve flake8 lint issues -ignore = E203, E231, E266, E501, W503 -exclude = - # TODO(https://github.com/googleapis/gapic-generator-python/issues/2333): - # Ensure that generated code passes flake8 lint - **/gapic/** - **/services/** - **/types/** - # Exclude Protobuf gencode - *_pb2.py - - # Standard linting exemptions. - **/.nox/** - __pycache__, - .git, - *.pyc, - conf.py diff --git a/owl-bot-staging/google-cloud-config/v1/LICENSE b/owl-bot-staging/google-cloud-config/v1/LICENSE deleted file mode 100644 index d64569567334..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/LICENSE +++ /dev/null @@ -1,202 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT 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/owl-bot-staging/google-cloud-config/v1/MANIFEST.in b/owl-bot-staging/google-cloud-config/v1/MANIFEST.in deleted file mode 100644 index dae249ec8976..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/MANIFEST.in +++ /dev/null @@ -1,20 +0,0 @@ -# -*- 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. -# -include README.rst LICENSE -recursive-include google *.py *.pyi *.json *.proto py.typed -recursive-include tests * -global-exclude *.py[co] -global-exclude __pycache__ diff --git a/owl-bot-staging/google-cloud-config/v1/README.rst b/owl-bot-staging/google-cloud-config/v1/README.rst deleted file mode 100644 index 80bc4c51622b..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/README.rst +++ /dev/null @@ -1,143 +0,0 @@ -Python Client for Google Cloud Config API -================================================= - -Quick Start ------------ - -In order to use this library, you first need to go through the following steps: - -1. `Select or create a Cloud Platform project.`_ -2. `Enable billing for your project.`_ -3. Enable the Google Cloud Config API. -4. `Setup Authentication.`_ - -.. _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 -.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html - -Installation -~~~~~~~~~~~~ - -Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to -create isolated Python environments. The basic problem it addresses is one of -dependencies and versions, and indirectly permissions. - -With `virtualenv`_, it's possible to install this library without needing system -install permissions, and without clashing with the installed system -dependencies. - -.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ - - -Mac/Linux -^^^^^^^^^ - -.. code-block:: console - - python3 -m venv - source /bin/activate - /bin/pip install /path/to/library - - -Windows -^^^^^^^ - -.. code-block:: console - - python3 -m venv - \Scripts\activate - \Scripts\pip.exe install \path\to\library - - -Logging -------- - -This library uses the standard Python :code:`logging` functionality to log some RPC events that could be of interest for debugging and monitoring purposes. -Note the following: - -#. Logs may contain sensitive information. Take care to **restrict access to the logs** if they are saved, whether it be on local storage or on Google Cloud Logging. -#. Google may refine the occurrence, level, and content of various log messages in this library without flagging such changes as breaking. **Do not depend on immutability of the logging events**. -#. By default, the logging events from this library are not handled. You must **explicitly configure log handling** using one of the mechanisms below. - - -Simple, environment-based configuration -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -To enable logging for this library without any changes in your code, set the :code:`GOOGLE_SDK_PYTHON_LOGGING_SCOPE` environment variable to a valid Google -logging scope. This configures handling of logging events (at level :code:`logging.DEBUG` or higher) from this library in a default manner, emitting the logged -messages in a structured format. It does not currently allow customizing the logging levels captured nor the handlers, formatters, etc. used for any logging -event. - -A logging scope is a period-separated namespace that begins with :code:`google`, identifying the Python module or package to log. - -- Valid logging scopes: :code:`google`, :code:`google.cloud.asset.v1`, :code:`google.api`, :code:`google.auth`, etc. -- Invalid logging scopes: :code:`foo`, :code:`123`, etc. - -**NOTE**: If the logging scope is invalid, the library does not set up any logging handlers. - - -Examples -^^^^^^^^ - -- Enabling the default handler for all Google-based loggers - -.. code-block:: console - - export GOOGLE_SDK_PYTHON_LOGGING_SCOPE=google - -- Enabling the default handler for a specific Google module (for a client library called :code:`library_v1`): - -.. code-block:: console - - export GOOGLE_SDK_PYTHON_LOGGING_SCOPE=google.cloud.library_v1 - - -Advanced, code-based configuration -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -You can also configure a valid logging scope using Python's standard `logging` mechanism. - - -Examples -^^^^^^^^ - -- Configuring a handler for all Google-based loggers - -.. code-block:: python - - import logging - - from google.cloud.translate_v3 import translate - - base_logger = logging.getLogger("google") - base_logger.addHandler(logging.StreamHandler()) - base_logger.setLevel(logging.DEBUG) - -- Configuring a handler for a specific Google module (for a client library called :code:`library_v1`): - -.. code-block:: python - - import logging - - from google.cloud.translate_v3 import translate - - base_logger = logging.getLogger("google.cloud.library_v1") - base_logger.addHandler(logging.StreamHandler()) - base_logger.setLevel(logging.DEBUG) - - -Logging details -~~~~~~~~~~~~~~~ - -#. Regardless of which of the mechanisms above you use to configure logging for this library, by default logging events are not propagated up to the root - logger from the `google`-level logger. If you need the events to be propagated to the root logger, you must explicitly set - :code:`logging.getLogger("google").propagate = True` in your code. -#. You can mix the different logging configurations above for different Google modules. For example, you may want use a code-based logging configuration for - one library, but decide you need to also set up environment-based logging configuration for another library. - - #. If you attempt to use both code-based and environment-based configuration for the same module, the environment-based configuration will be ineffectual - if the code -based configuration gets applied first. - -#. The Google-specific logging configurations (default handlers for environment-based configuration; not propagating logging events to the root logger) get - executed the first time *any* client library is instantiated in your application, and only if the affected loggers have not been previously configured. - (This is the reason for 2.i. above.) diff --git a/owl-bot-staging/google-cloud-config/v1/docs/_static/custom.css b/owl-bot-staging/google-cloud-config/v1/docs/_static/custom.css deleted file mode 100644 index b0a295464b23..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/docs/_static/custom.css +++ /dev/null @@ -1,20 +0,0 @@ -div#python2-eol { - border-color: red; - border-width: medium; -} - -/* Ensure minimum width for 'Parameters' / 'Returns' column */ -dl.field-list > dt { - min-width: 100px -} - -/* Insert space between methods for readability */ -dl.method { - padding-top: 10px; - padding-bottom: 10px -} - -/* Insert empty space between classes */ -dl.class { - padding-bottom: 50px -} diff --git a/owl-bot-staging/google-cloud-config/v1/docs/_templates/layout.html b/owl-bot-staging/google-cloud-config/v1/docs/_templates/layout.html deleted file mode 100644 index 95e9c77fcfe1..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/docs/_templates/layout.html +++ /dev/null @@ -1,50 +0,0 @@ - -{% extends "!layout.html" %} -{%- block content %} -{%- if theme_fixed_sidebar|lower == 'true' %} -
- {{ sidebar() }} - {%- block document %} -
- {%- if render_sidebar %} -
- {%- endif %} - - {%- block relbar_top %} - {%- if theme_show_relbar_top|tobool %} - - {%- endif %} - {% endblock %} - -
-
- As of January 1, 2020 this library no longer supports Python 2 on the latest released version. - Library versions released prior to that date will continue to be available. For more information please - visit Python 2 support on Google Cloud. -
- {% block body %} {% endblock %} -
- - {%- block relbar_bottom %} - {%- if theme_show_relbar_bottom|tobool %} - - {%- endif %} - {% endblock %} - - {%- if render_sidebar %} -
- {%- endif %} -
- {%- endblock %} -
-
-{%- else %} -{{ super() }} -{%- endif %} -{%- endblock %} diff --git a/owl-bot-staging/google-cloud-config/v1/docs/conf.py b/owl-bot-staging/google-cloud-config/v1/docs/conf.py deleted file mode 100644 index 7935eaba9a58..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/docs/conf.py +++ /dev/null @@ -1,385 +0,0 @@ -# -*- 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. -# -# -# google-cloud-config documentation build configuration file -# -# This file is execfile()d with the current directory set to its -# containing dir. -# -# Note that not all possible configuration values are present in this -# autogenerated file. -# -# All configuration values have a default; values that are commented out -# serve to show the default. - -import sys -import os -import shlex - -# If extensions (or modules to document with autodoc) are in another directory, -# add these directories to sys.path here. If the directory is relative to the -# documentation root, use os.path.abspath to make it absolute, like shown here. -sys.path.insert(0, os.path.abspath("..")) - -# For plugins that can not read conf.py. -# See also: https://github.com/docascode/sphinx-docfx-yaml/issues/85 -sys.path.insert(0, os.path.abspath(".")) - -__version__ = "" - -# -- General configuration ------------------------------------------------ - -# If your documentation needs a minimal Sphinx version, state it here. -needs_sphinx = "4.5.0" - -# Add any Sphinx extension module names here, as strings. They can be -# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom -# ones. -extensions = [ - "sphinx.ext.autodoc", - "sphinx.ext.autosummary", - "sphinx.ext.intersphinx", - "sphinx.ext.coverage", - "sphinx.ext.doctest", - "sphinx.ext.napoleon", - "sphinx.ext.todo", - "sphinx.ext.viewcode", - "recommonmark", -] - -# autodoc/autosummary flags -autoclass_content = "both" -autodoc_default_options = {"members": True} -autosummary_generate = True - - -# Add any paths that contain templates here, relative to this directory. -templates_path = ["_templates"] - -# The suffix(es) of source filenames. -# You can specify multiple suffix as a list of string: -# source_suffix = ['.rst', '.md'] -source_suffix = [".rst", ".md"] - -# The encoding of source files. -# source_encoding = 'utf-8-sig' - -# The root toctree document. -root_doc = "index" - -# General information about the project. -project = u"google-cloud-config" -copyright = u"2025, Google, LLC" -author = u"Google APIs" - -# The version info for the project you're documenting, acts as replacement for -# |version| and |release|, also used in various other places throughout the -# built documents. -# -# The full version, including alpha/beta/rc tags. -release = __version__ -# The short X.Y version. -version = ".".join(release.split(".")[0:2]) - -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -# -# This is also used if you do content translation via gettext catalogs. -# Usually you set "language" from the command line for these cases. -language = None - -# There are two options for replacing |today|: either, you set today to some -# non-false value, then it is used: -# today = '' -# Else, today_fmt is used as the format for a strftime call. -# today_fmt = '%B %d, %Y' - -# List of patterns, relative to source directory, that match files and -# directories to ignore when looking for source files. -exclude_patterns = [ - "_build", - "**/.nox/**/*", - "samples/AUTHORING_GUIDE.md", - "samples/CONTRIBUTING.md", - "samples/snippets/README.rst", -] - -# The reST default role (used for this markup: `text`) to use for all -# documents. -# default_role = None - -# If true, '()' will be appended to :func: etc. cross-reference text. -# add_function_parentheses = True - -# If true, the current module name will be prepended to all description -# unit titles (such as .. function::). -# add_module_names = True - -# If true, sectionauthor and moduleauthor directives will be shown in the -# output. They are ignored by default. -# show_authors = False - -# The name of the Pygments (syntax highlighting) style to use. -pygments_style = "sphinx" - -# A list of ignored prefixes for module index sorting. -# modindex_common_prefix = [] - -# If true, keep warnings as "system message" paragraphs in the built documents. -# keep_warnings = False - -# If true, `todo` and `todoList` produce output, else they produce nothing. -todo_include_todos = True - - -# -- Options for HTML output ---------------------------------------------- - -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. -html_theme = "alabaster" - -# Theme options are theme-specific and customize the look and feel of a theme -# further. For a list of options available for each theme, see the -# documentation. -html_theme_options = { - "description": "Google Cloud Client Libraries for google-cloud-config", - "github_user": "googleapis", - "github_repo": "google-cloud-python", - "github_banner": True, - "font_family": "'Roboto', Georgia, sans", - "head_font_family": "'Roboto', Georgia, serif", - "code_font_family": "'Roboto Mono', 'Consolas', monospace", -} - -# Add any paths that contain custom themes here, relative to this directory. -# html_theme_path = [] - -# The name for this set of Sphinx documents. If None, it defaults to -# " v documentation". -# html_title = None - -# A shorter title for the navigation bar. Default is the same as html_title. -# html_short_title = None - -# The name of an image file (relative to this directory) to place at the top -# of the sidebar. -# html_logo = None - -# The name of an image file (within the static path) to use as favicon of the -# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 -# pixels large. -# html_favicon = None - -# Add any paths that contain custom static files (such as style sheets) here, -# relative to this directory. They are copied after the builtin static files, -# so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ["_static"] - -# Add any extra paths that contain custom files (such as robots.txt or -# .htaccess) here, relative to this directory. These files are copied -# directly to the root of the documentation. -# html_extra_path = [] - -# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, -# using the given strftime format. -# html_last_updated_fmt = '%b %d, %Y' - -# If true, SmartyPants will be used to convert quotes and dashes to -# typographically correct entities. -# html_use_smartypants = True - -# Custom sidebar templates, maps document names to template names. -# html_sidebars = {} - -# Additional templates that should be rendered to pages, maps page names to -# template names. -# html_additional_pages = {} - -# If false, no module index is generated. -# html_domain_indices = True - -# If false, no index is generated. -# html_use_index = True - -# If true, the index is split into individual pages for each letter. -# html_split_index = False - -# If true, links to the reST sources are added to the pages. -# html_show_sourcelink = True - -# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. -# html_show_sphinx = True - -# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. -# html_show_copyright = True - -# If true, an OpenSearch description file will be output, and all pages will -# contain a tag referring to it. The value of this option must be the -# base URL from which the finished HTML is served. -# html_use_opensearch = '' - -# This is the file name suffix for HTML files (e.g. ".xhtml"). -# html_file_suffix = None - -# Language to be used for generating the HTML full-text search index. -# Sphinx supports the following languages: -# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' -# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' -# html_search_language = 'en' - -# A dictionary with options for the search language support, empty by default. -# Now only 'ja' uses this config value -# html_search_options = {'type': 'default'} - -# The name of a javascript file (relative to the configuration directory) that -# implements a search results scorer. If empty, the default will be used. -# html_search_scorer = 'scorer.js' - -# Output file base name for HTML help builder. -htmlhelp_basename = "google-cloud-config-doc" - -# -- Options for warnings ------------------------------------------------------ - - -suppress_warnings = [ - # Temporarily suppress this to avoid "more than one target found for - # cross-reference" warning, which are intractable for us to avoid while in - # a mono-repo. - # See https://github.com/sphinx-doc/sphinx/blob - # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 - "ref.python" -] - -# -- Options for LaTeX output --------------------------------------------- - -latex_elements = { - # The paper size ('letterpaper' or 'a4paper'). - # 'papersize': 'letterpaper', - # The font size ('10pt', '11pt' or '12pt'). - # 'pointsize': '10pt', - # Additional stuff for the LaTeX preamble. - # 'preamble': '', - # Latex figure (float) alignment - # 'figure_align': 'htbp', -} - -# Grouping the document tree into LaTeX files. List of tuples -# (source start file, target name, title, -# author, documentclass [howto, manual, or own class]). -latex_documents = [ - ( - root_doc, - "google-cloud-config.tex", - u"google-cloud-config Documentation", - author, - "manual", - ) -] - -# The name of an image file (relative to this directory) to place at the top of -# the title page. -# latex_logo = None - -# For "manual" documents, if this is true, then toplevel headings are parts, -# not chapters. -# latex_use_parts = False - -# If true, show page references after internal links. -# latex_show_pagerefs = False - -# If true, show URL addresses after external links. -# latex_show_urls = False - -# Documents to append as an appendix to all manuals. -# latex_appendices = [] - -# If false, no module index is generated. -# latex_domain_indices = True - - -# -- Options for manual page output --------------------------------------- - -# One entry per manual page. List of tuples -# (source start file, name, description, authors, manual section). -man_pages = [ - ( - root_doc, - "google-cloud-config", - "google-cloud-config Documentation", - [author], - 1, - ) -] - -# If true, show URL addresses after external links. -# man_show_urls = False - - -# -- Options for Texinfo output ------------------------------------------- - -# Grouping the document tree into Texinfo files. List of tuples -# (source start file, target name, title, author, -# dir menu entry, description, category) -texinfo_documents = [ - ( - root_doc, - "google-cloud-config", - "google-cloud-config Documentation", - author, - "google-cloud-config", - "google-cloud-config Library", - "APIs", - ) -] - -# Documents to append as an appendix to all manuals. -# texinfo_appendices = [] - -# If false, no module index is generated. -# texinfo_domain_indices = True - -# How to display URL addresses: 'footnote', 'no', or 'inline'. -# texinfo_show_urls = 'footnote' - -# If true, do not generate a @detailmenu in the "Top" node's menu. -# texinfo_no_detailmenu = False - - -# Example configuration for intersphinx: refer to the Python standard library. -intersphinx_mapping = { - "python": ("https://python.readthedocs.org/en/latest/", None), - "google-auth": ("https://googleapis.dev/python/google-auth/latest/", None), - "google.api_core": ( - "https://googleapis.dev/python/google-api-core/latest/", - None, - ), - "grpc": ("https://grpc.github.io/grpc/python/", None), - "proto-plus": ("https://proto-plus-python.readthedocs.io/en/latest/", None), - "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), -} - - -# Napoleon settings -napoleon_google_docstring = True -napoleon_numpy_docstring = True -napoleon_include_private_with_doc = False -napoleon_include_special_with_doc = True -napoleon_use_admonition_for_examples = False -napoleon_use_admonition_for_notes = False -napoleon_use_admonition_for_references = False -napoleon_use_ivar = False -napoleon_use_param = True -napoleon_use_rtype = True diff --git a/owl-bot-staging/google-cloud-config/v1/docs/config_v1/config.rst b/owl-bot-staging/google-cloud-config/v1/docs/config_v1/config.rst deleted file mode 100644 index 7ad09d4ba002..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/docs/config_v1/config.rst +++ /dev/null @@ -1,10 +0,0 @@ -Config ------------------------- - -.. automodule:: google.cloud.config_v1.services.config - :members: - :inherited-members: - -.. automodule:: google.cloud.config_v1.services.config.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/google-cloud-config/v1/docs/config_v1/services_.rst b/owl-bot-staging/google-cloud-config/v1/docs/config_v1/services_.rst deleted file mode 100644 index 51dabd45ae67..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/docs/config_v1/services_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Services for Google Cloud Config v1 API -======================================= -.. toctree:: - :maxdepth: 2 - - config diff --git a/owl-bot-staging/google-cloud-config/v1/docs/config_v1/types_.rst b/owl-bot-staging/google-cloud-config/v1/docs/config_v1/types_.rst deleted file mode 100644 index 33bb93d6c861..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/docs/config_v1/types_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Types for Google Cloud Config v1 API -==================================== - -.. automodule:: google.cloud.config_v1.types - :members: - :show-inheritance: diff --git a/owl-bot-staging/google-cloud-config/v1/docs/index.rst b/owl-bot-staging/google-cloud-config/v1/docs/index.rst deleted file mode 100644 index 0bd88733b91c..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/docs/index.rst +++ /dev/null @@ -1,10 +0,0 @@ -.. include:: multiprocessing.rst - - -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - config_v1/services_ - config_v1/types_ diff --git a/owl-bot-staging/google-cloud-config/v1/docs/multiprocessing.rst b/owl-bot-staging/google-cloud-config/v1/docs/multiprocessing.rst deleted file mode 100644 index 536d17b2ea65..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/docs/multiprocessing.rst +++ /dev/null @@ -1,7 +0,0 @@ -.. note:: - - Because this client uses :mod:`grpc` library, it is safe to - share instances across threads. In multiprocessing scenarios, the best - practice is to create client instances *after* the invocation of - :func:`os.fork` by :class:`multiprocessing.pool.Pool` or - :class:`multiprocessing.Process`. diff --git a/owl-bot-staging/google-cloud-config/v1/google/cloud/config/__init__.py b/owl-bot-staging/google-cloud-config/v1/google/cloud/config/__init__.py deleted file mode 100644 index 79797d85e9c1..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/google/cloud/config/__init__.py +++ /dev/null @@ -1,153 +0,0 @@ -# -*- 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. -# -from google.cloud.config import gapic_version as package_version - -__version__ = package_version.__version__ - - -from google.cloud.config_v1.services.config.client import ConfigClient -from google.cloud.config_v1.services.config.async_client import ConfigAsyncClient - -from google.cloud.config_v1.types.config import ApplyResults -from google.cloud.config_v1.types.config import CreateDeploymentRequest -from google.cloud.config_v1.types.config import CreatePreviewRequest -from google.cloud.config_v1.types.config import DeleteDeploymentRequest -from google.cloud.config_v1.types.config import DeletePreviewRequest -from google.cloud.config_v1.types.config import DeleteStatefileRequest -from google.cloud.config_v1.types.config import Deployment -from google.cloud.config_v1.types.config import DeploymentOperationMetadata -from google.cloud.config_v1.types.config import ExportDeploymentStatefileRequest -from google.cloud.config_v1.types.config import ExportLockInfoRequest -from google.cloud.config_v1.types.config import ExportPreviewResultRequest -from google.cloud.config_v1.types.config import ExportPreviewResultResponse -from google.cloud.config_v1.types.config import ExportRevisionStatefileRequest -from google.cloud.config_v1.types.config import GetDeploymentRequest -from google.cloud.config_v1.types.config import GetPreviewRequest -from google.cloud.config_v1.types.config import GetResourceChangeRequest -from google.cloud.config_v1.types.config import GetResourceDriftRequest -from google.cloud.config_v1.types.config import GetResourceRequest -from google.cloud.config_v1.types.config import GetRevisionRequest -from google.cloud.config_v1.types.config import GetTerraformVersionRequest -from google.cloud.config_v1.types.config import GitSource -from google.cloud.config_v1.types.config import ImportStatefileRequest -from google.cloud.config_v1.types.config import ListDeploymentsRequest -from google.cloud.config_v1.types.config import ListDeploymentsResponse -from google.cloud.config_v1.types.config import ListPreviewsRequest -from google.cloud.config_v1.types.config import ListPreviewsResponse -from google.cloud.config_v1.types.config import ListResourceChangesRequest -from google.cloud.config_v1.types.config import ListResourceChangesResponse -from google.cloud.config_v1.types.config import ListResourceDriftsRequest -from google.cloud.config_v1.types.config import ListResourceDriftsResponse -from google.cloud.config_v1.types.config import ListResourcesRequest -from google.cloud.config_v1.types.config import ListResourcesResponse -from google.cloud.config_v1.types.config import ListRevisionsRequest -from google.cloud.config_v1.types.config import ListRevisionsResponse -from google.cloud.config_v1.types.config import ListTerraformVersionsRequest -from google.cloud.config_v1.types.config import ListTerraformVersionsResponse -from google.cloud.config_v1.types.config import LockDeploymentRequest -from google.cloud.config_v1.types.config import LockInfo -from google.cloud.config_v1.types.config import OperationMetadata -from google.cloud.config_v1.types.config import Preview -from google.cloud.config_v1.types.config import PreviewArtifacts -from google.cloud.config_v1.types.config import PreviewOperationMetadata -from google.cloud.config_v1.types.config import PreviewResult -from google.cloud.config_v1.types.config import PropertyChange -from google.cloud.config_v1.types.config import PropertyDrift -from google.cloud.config_v1.types.config import ProviderConfig -from google.cloud.config_v1.types.config import Resource -from google.cloud.config_v1.types.config import ResourceCAIInfo -from google.cloud.config_v1.types.config import ResourceChange -from google.cloud.config_v1.types.config import ResourceChangeTerraformInfo -from google.cloud.config_v1.types.config import ResourceDrift -from google.cloud.config_v1.types.config import ResourceDriftTerraformInfo -from google.cloud.config_v1.types.config import ResourceTerraformInfo -from google.cloud.config_v1.types.config import Revision -from google.cloud.config_v1.types.config import Statefile -from google.cloud.config_v1.types.config import TerraformBlueprint -from google.cloud.config_v1.types.config import TerraformError -from google.cloud.config_v1.types.config import TerraformOutput -from google.cloud.config_v1.types.config import TerraformVariable -from google.cloud.config_v1.types.config import TerraformVersion -from google.cloud.config_v1.types.config import UnlockDeploymentRequest -from google.cloud.config_v1.types.config import UpdateDeploymentRequest -from google.cloud.config_v1.types.config import QuotaValidation - -__all__ = ('ConfigClient', - 'ConfigAsyncClient', - 'ApplyResults', - 'CreateDeploymentRequest', - 'CreatePreviewRequest', - 'DeleteDeploymentRequest', - 'DeletePreviewRequest', - 'DeleteStatefileRequest', - 'Deployment', - 'DeploymentOperationMetadata', - 'ExportDeploymentStatefileRequest', - 'ExportLockInfoRequest', - 'ExportPreviewResultRequest', - 'ExportPreviewResultResponse', - 'ExportRevisionStatefileRequest', - 'GetDeploymentRequest', - 'GetPreviewRequest', - 'GetResourceChangeRequest', - 'GetResourceDriftRequest', - 'GetResourceRequest', - 'GetRevisionRequest', - 'GetTerraformVersionRequest', - 'GitSource', - 'ImportStatefileRequest', - 'ListDeploymentsRequest', - 'ListDeploymentsResponse', - 'ListPreviewsRequest', - 'ListPreviewsResponse', - 'ListResourceChangesRequest', - 'ListResourceChangesResponse', - 'ListResourceDriftsRequest', - 'ListResourceDriftsResponse', - 'ListResourcesRequest', - 'ListResourcesResponse', - 'ListRevisionsRequest', - 'ListRevisionsResponse', - 'ListTerraformVersionsRequest', - 'ListTerraformVersionsResponse', - 'LockDeploymentRequest', - 'LockInfo', - 'OperationMetadata', - 'Preview', - 'PreviewArtifacts', - 'PreviewOperationMetadata', - 'PreviewResult', - 'PropertyChange', - 'PropertyDrift', - 'ProviderConfig', - 'Resource', - 'ResourceCAIInfo', - 'ResourceChange', - 'ResourceChangeTerraformInfo', - 'ResourceDrift', - 'ResourceDriftTerraformInfo', - 'ResourceTerraformInfo', - 'Revision', - 'Statefile', - 'TerraformBlueprint', - 'TerraformError', - 'TerraformOutput', - 'TerraformVariable', - 'TerraformVersion', - 'UnlockDeploymentRequest', - 'UpdateDeploymentRequest', - 'QuotaValidation', -) diff --git a/owl-bot-staging/google-cloud-config/v1/google/cloud/config/gapic_version.py b/owl-bot-staging/google-cloud-config/v1/google/cloud/config/gapic_version.py deleted file mode 100644 index 20a9cd975b02..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/google/cloud/config/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- 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. -# -__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-cloud-config/v1/google/cloud/config/py.typed b/owl-bot-staging/google-cloud-config/v1/google/cloud/config/py.typed deleted file mode 100644 index f4fe63d2606c..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/google/cloud/config/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-config package uses inline types. diff --git a/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/__init__.py b/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/__init__.py deleted file mode 100644 index 0a5f53709651..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/__init__.py +++ /dev/null @@ -1,154 +0,0 @@ -# -*- 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. -# -from google.cloud.config_v1 import gapic_version as package_version - -__version__ = package_version.__version__ - - -from .services.config import ConfigClient -from .services.config import ConfigAsyncClient - -from .types.config import ApplyResults -from .types.config import CreateDeploymentRequest -from .types.config import CreatePreviewRequest -from .types.config import DeleteDeploymentRequest -from .types.config import DeletePreviewRequest -from .types.config import DeleteStatefileRequest -from .types.config import Deployment -from .types.config import DeploymentOperationMetadata -from .types.config import ExportDeploymentStatefileRequest -from .types.config import ExportLockInfoRequest -from .types.config import ExportPreviewResultRequest -from .types.config import ExportPreviewResultResponse -from .types.config import ExportRevisionStatefileRequest -from .types.config import GetDeploymentRequest -from .types.config import GetPreviewRequest -from .types.config import GetResourceChangeRequest -from .types.config import GetResourceDriftRequest -from .types.config import GetResourceRequest -from .types.config import GetRevisionRequest -from .types.config import GetTerraformVersionRequest -from .types.config import GitSource -from .types.config import ImportStatefileRequest -from .types.config import ListDeploymentsRequest -from .types.config import ListDeploymentsResponse -from .types.config import ListPreviewsRequest -from .types.config import ListPreviewsResponse -from .types.config import ListResourceChangesRequest -from .types.config import ListResourceChangesResponse -from .types.config import ListResourceDriftsRequest -from .types.config import ListResourceDriftsResponse -from .types.config import ListResourcesRequest -from .types.config import ListResourcesResponse -from .types.config import ListRevisionsRequest -from .types.config import ListRevisionsResponse -from .types.config import ListTerraformVersionsRequest -from .types.config import ListTerraformVersionsResponse -from .types.config import LockDeploymentRequest -from .types.config import LockInfo -from .types.config import OperationMetadata -from .types.config import Preview -from .types.config import PreviewArtifacts -from .types.config import PreviewOperationMetadata -from .types.config import PreviewResult -from .types.config import PropertyChange -from .types.config import PropertyDrift -from .types.config import ProviderConfig -from .types.config import Resource -from .types.config import ResourceCAIInfo -from .types.config import ResourceChange -from .types.config import ResourceChangeTerraformInfo -from .types.config import ResourceDrift -from .types.config import ResourceDriftTerraformInfo -from .types.config import ResourceTerraformInfo -from .types.config import Revision -from .types.config import Statefile -from .types.config import TerraformBlueprint -from .types.config import TerraformError -from .types.config import TerraformOutput -from .types.config import TerraformVariable -from .types.config import TerraformVersion -from .types.config import UnlockDeploymentRequest -from .types.config import UpdateDeploymentRequest -from .types.config import QuotaValidation - -__all__ = ( - 'ConfigAsyncClient', -'ApplyResults', -'ConfigClient', -'CreateDeploymentRequest', -'CreatePreviewRequest', -'DeleteDeploymentRequest', -'DeletePreviewRequest', -'DeleteStatefileRequest', -'Deployment', -'DeploymentOperationMetadata', -'ExportDeploymentStatefileRequest', -'ExportLockInfoRequest', -'ExportPreviewResultRequest', -'ExportPreviewResultResponse', -'ExportRevisionStatefileRequest', -'GetDeploymentRequest', -'GetPreviewRequest', -'GetResourceChangeRequest', -'GetResourceDriftRequest', -'GetResourceRequest', -'GetRevisionRequest', -'GetTerraformVersionRequest', -'GitSource', -'ImportStatefileRequest', -'ListDeploymentsRequest', -'ListDeploymentsResponse', -'ListPreviewsRequest', -'ListPreviewsResponse', -'ListResourceChangesRequest', -'ListResourceChangesResponse', -'ListResourceDriftsRequest', -'ListResourceDriftsResponse', -'ListResourcesRequest', -'ListResourcesResponse', -'ListRevisionsRequest', -'ListRevisionsResponse', -'ListTerraformVersionsRequest', -'ListTerraformVersionsResponse', -'LockDeploymentRequest', -'LockInfo', -'OperationMetadata', -'Preview', -'PreviewArtifacts', -'PreviewOperationMetadata', -'PreviewResult', -'PropertyChange', -'PropertyDrift', -'ProviderConfig', -'QuotaValidation', -'Resource', -'ResourceCAIInfo', -'ResourceChange', -'ResourceChangeTerraformInfo', -'ResourceDrift', -'ResourceDriftTerraformInfo', -'ResourceTerraformInfo', -'Revision', -'Statefile', -'TerraformBlueprint', -'TerraformError', -'TerraformOutput', -'TerraformVariable', -'TerraformVersion', -'UnlockDeploymentRequest', -'UpdateDeploymentRequest', -) diff --git a/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/gapic_metadata.json b/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/gapic_metadata.json deleted file mode 100644 index fd2c8bc6dd14..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/gapic_metadata.json +++ /dev/null @@ -1,433 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.cloud.config_v1", - "protoPackage": "google.cloud.config.v1", - "schema": "1.0", - "services": { - "Config": { - "clients": { - "grpc": { - "libraryClient": "ConfigClient", - "rpcs": { - "CreateDeployment": { - "methods": [ - "create_deployment" - ] - }, - "CreatePreview": { - "methods": [ - "create_preview" - ] - }, - "DeleteDeployment": { - "methods": [ - "delete_deployment" - ] - }, - "DeletePreview": { - "methods": [ - "delete_preview" - ] - }, - "DeleteStatefile": { - "methods": [ - "delete_statefile" - ] - }, - "ExportDeploymentStatefile": { - "methods": [ - "export_deployment_statefile" - ] - }, - "ExportLockInfo": { - "methods": [ - "export_lock_info" - ] - }, - "ExportPreviewResult": { - "methods": [ - "export_preview_result" - ] - }, - "ExportRevisionStatefile": { - "methods": [ - "export_revision_statefile" - ] - }, - "GetDeployment": { - "methods": [ - "get_deployment" - ] - }, - "GetPreview": { - "methods": [ - "get_preview" - ] - }, - "GetResource": { - "methods": [ - "get_resource" - ] - }, - "GetResourceChange": { - "methods": [ - "get_resource_change" - ] - }, - "GetResourceDrift": { - "methods": [ - "get_resource_drift" - ] - }, - "GetRevision": { - "methods": [ - "get_revision" - ] - }, - "GetTerraformVersion": { - "methods": [ - "get_terraform_version" - ] - }, - "ImportStatefile": { - "methods": [ - "import_statefile" - ] - }, - "ListDeployments": { - "methods": [ - "list_deployments" - ] - }, - "ListPreviews": { - "methods": [ - "list_previews" - ] - }, - "ListResourceChanges": { - "methods": [ - "list_resource_changes" - ] - }, - "ListResourceDrifts": { - "methods": [ - "list_resource_drifts" - ] - }, - "ListResources": { - "methods": [ - "list_resources" - ] - }, - "ListRevisions": { - "methods": [ - "list_revisions" - ] - }, - "ListTerraformVersions": { - "methods": [ - "list_terraform_versions" - ] - }, - "LockDeployment": { - "methods": [ - "lock_deployment" - ] - }, - "UnlockDeployment": { - "methods": [ - "unlock_deployment" - ] - }, - "UpdateDeployment": { - "methods": [ - "update_deployment" - ] - } - } - }, - "grpc-async": { - "libraryClient": "ConfigAsyncClient", - "rpcs": { - "CreateDeployment": { - "methods": [ - "create_deployment" - ] - }, - "CreatePreview": { - "methods": [ - "create_preview" - ] - }, - "DeleteDeployment": { - "methods": [ - "delete_deployment" - ] - }, - "DeletePreview": { - "methods": [ - "delete_preview" - ] - }, - "DeleteStatefile": { - "methods": [ - "delete_statefile" - ] - }, - "ExportDeploymentStatefile": { - "methods": [ - "export_deployment_statefile" - ] - }, - "ExportLockInfo": { - "methods": [ - "export_lock_info" - ] - }, - "ExportPreviewResult": { - "methods": [ - "export_preview_result" - ] - }, - "ExportRevisionStatefile": { - "methods": [ - "export_revision_statefile" - ] - }, - "GetDeployment": { - "methods": [ - "get_deployment" - ] - }, - "GetPreview": { - "methods": [ - "get_preview" - ] - }, - "GetResource": { - "methods": [ - "get_resource" - ] - }, - "GetResourceChange": { - "methods": [ - "get_resource_change" - ] - }, - "GetResourceDrift": { - "methods": [ - "get_resource_drift" - ] - }, - "GetRevision": { - "methods": [ - "get_revision" - ] - }, - "GetTerraformVersion": { - "methods": [ - "get_terraform_version" - ] - }, - "ImportStatefile": { - "methods": [ - "import_statefile" - ] - }, - "ListDeployments": { - "methods": [ - "list_deployments" - ] - }, - "ListPreviews": { - "methods": [ - "list_previews" - ] - }, - "ListResourceChanges": { - "methods": [ - "list_resource_changes" - ] - }, - "ListResourceDrifts": { - "methods": [ - "list_resource_drifts" - ] - }, - "ListResources": { - "methods": [ - "list_resources" - ] - }, - "ListRevisions": { - "methods": [ - "list_revisions" - ] - }, - "ListTerraformVersions": { - "methods": [ - "list_terraform_versions" - ] - }, - "LockDeployment": { - "methods": [ - "lock_deployment" - ] - }, - "UnlockDeployment": { - "methods": [ - "unlock_deployment" - ] - }, - "UpdateDeployment": { - "methods": [ - "update_deployment" - ] - } - } - }, - "rest": { - "libraryClient": "ConfigClient", - "rpcs": { - "CreateDeployment": { - "methods": [ - "create_deployment" - ] - }, - "CreatePreview": { - "methods": [ - "create_preview" - ] - }, - "DeleteDeployment": { - "methods": [ - "delete_deployment" - ] - }, - "DeletePreview": { - "methods": [ - "delete_preview" - ] - }, - "DeleteStatefile": { - "methods": [ - "delete_statefile" - ] - }, - "ExportDeploymentStatefile": { - "methods": [ - "export_deployment_statefile" - ] - }, - "ExportLockInfo": { - "methods": [ - "export_lock_info" - ] - }, - "ExportPreviewResult": { - "methods": [ - "export_preview_result" - ] - }, - "ExportRevisionStatefile": { - "methods": [ - "export_revision_statefile" - ] - }, - "GetDeployment": { - "methods": [ - "get_deployment" - ] - }, - "GetPreview": { - "methods": [ - "get_preview" - ] - }, - "GetResource": { - "methods": [ - "get_resource" - ] - }, - "GetResourceChange": { - "methods": [ - "get_resource_change" - ] - }, - "GetResourceDrift": { - "methods": [ - "get_resource_drift" - ] - }, - "GetRevision": { - "methods": [ - "get_revision" - ] - }, - "GetTerraformVersion": { - "methods": [ - "get_terraform_version" - ] - }, - "ImportStatefile": { - "methods": [ - "import_statefile" - ] - }, - "ListDeployments": { - "methods": [ - "list_deployments" - ] - }, - "ListPreviews": { - "methods": [ - "list_previews" - ] - }, - "ListResourceChanges": { - "methods": [ - "list_resource_changes" - ] - }, - "ListResourceDrifts": { - "methods": [ - "list_resource_drifts" - ] - }, - "ListResources": { - "methods": [ - "list_resources" - ] - }, - "ListRevisions": { - "methods": [ - "list_revisions" - ] - }, - "ListTerraformVersions": { - "methods": [ - "list_terraform_versions" - ] - }, - "LockDeployment": { - "methods": [ - "lock_deployment" - ] - }, - "UnlockDeployment": { - "methods": [ - "unlock_deployment" - ] - }, - "UpdateDeployment": { - "methods": [ - "update_deployment" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/gapic_version.py b/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/gapic_version.py deleted file mode 100644 index 20a9cd975b02..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- 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. -# -__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/py.typed b/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/py.typed deleted file mode 100644 index f4fe63d2606c..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-config package uses inline types. diff --git a/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/__init__.py b/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/__init__.py deleted file mode 100644 index cbf94b283c70..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- 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. -# diff --git a/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/__init__.py b/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/__init__.py deleted file mode 100644 index 1b691a8b10de..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- 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. -# -from .client import ConfigClient -from .async_client import ConfigAsyncClient - -__all__ = ( - 'ConfigClient', - 'ConfigAsyncClient', -) diff --git a/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/async_client.py b/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/async_client.py deleted file mode 100644 index d4fe64005767..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/async_client.py +++ /dev/null @@ -1,4004 +0,0 @@ -# -*- 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. -# -import logging as std_logging -from collections import OrderedDict -import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.config_v1 import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -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.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore -import google.protobuf - - -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.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.config_v1.services.config import pagers -from google.cloud.config_v1.types import config -from google.cloud.location import locations_pb2 # type: ignore -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore -from .transports.base import ConfigTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import ConfigGrpcAsyncIOTransport -from .client import ConfigClient - -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 ConfigAsyncClient: - """Infrastructure Manager is a managed service that automates - the deployment and management of Google Cloud infrastructure - resources. - """ - - _client: ConfigClient - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = ConfigClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = ConfigClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = ConfigClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = ConfigClient._DEFAULT_UNIVERSE - - deployment_path = staticmethod(ConfigClient.deployment_path) - parse_deployment_path = staticmethod(ConfigClient.parse_deployment_path) - preview_path = staticmethod(ConfigClient.preview_path) - parse_preview_path = staticmethod(ConfigClient.parse_preview_path) - resource_path = staticmethod(ConfigClient.resource_path) - parse_resource_path = staticmethod(ConfigClient.parse_resource_path) - resource_change_path = staticmethod(ConfigClient.resource_change_path) - parse_resource_change_path = staticmethod(ConfigClient.parse_resource_change_path) - resource_drift_path = staticmethod(ConfigClient.resource_drift_path) - parse_resource_drift_path = staticmethod(ConfigClient.parse_resource_drift_path) - revision_path = staticmethod(ConfigClient.revision_path) - parse_revision_path = staticmethod(ConfigClient.parse_revision_path) - service_account_path = staticmethod(ConfigClient.service_account_path) - parse_service_account_path = staticmethod(ConfigClient.parse_service_account_path) - terraform_version_path = staticmethod(ConfigClient.terraform_version_path) - parse_terraform_version_path = staticmethod(ConfigClient.parse_terraform_version_path) - worker_pool_path = staticmethod(ConfigClient.worker_pool_path) - parse_worker_pool_path = staticmethod(ConfigClient.parse_worker_pool_path) - common_billing_account_path = staticmethod(ConfigClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(ConfigClient.parse_common_billing_account_path) - common_folder_path = staticmethod(ConfigClient.common_folder_path) - parse_common_folder_path = staticmethod(ConfigClient.parse_common_folder_path) - common_organization_path = staticmethod(ConfigClient.common_organization_path) - parse_common_organization_path = staticmethod(ConfigClient.parse_common_organization_path) - common_project_path = staticmethod(ConfigClient.common_project_path) - parse_common_project_path = staticmethod(ConfigClient.parse_common_project_path) - common_location_path = staticmethod(ConfigClient.common_location_path) - parse_common_location_path = staticmethod(ConfigClient.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: - ConfigAsyncClient: The constructed client. - """ - return ConfigClient.from_service_account_info.__func__(ConfigAsyncClient, info, *args, **kwargs) # type: ignore - - @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: - ConfigAsyncClient: The constructed client. - """ - return ConfigClient.from_service_account_file.__func__(ConfigAsyncClient, filename, *args, **kwargs) # type: ignore - - 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 ConfigClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> ConfigTransport: - """Returns the transport used by the client instance. - - Returns: - ConfigTransport: The transport used by the client instance. - """ - return self._client.transport - - @property - def api_endpoint(self): - """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 = ConfigClient.get_transport_class - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, ConfigTransport, Callable[..., ConfigTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the config 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,ConfigTransport,Callable[..., ConfigTransport]]]): - 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 ConfigTransport 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 = ConfigClient( - 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.config_v1.ConfigAsyncClient`.", - extra = { - "serviceName": "google.cloud.config.v1.Config", - "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.config.v1.Config", - "credentialsType": None, - } - ) - - async def list_deployments(self, - request: Optional[Union[config.ListDeploymentsRequest, 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.ListDeploymentsAsyncPager: - r"""Lists [Deployment][google.cloud.config.v1.Deployment]s 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 config_v1 - - async def sample_list_deployments(): - # Create a client - client = config_v1.ConfigAsyncClient() - - # Initialize request argument(s) - request = config_v1.ListDeploymentsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_deployments(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.config_v1.types.ListDeploymentsRequest, dict]]): - The request object. - parent (:class:`str`): - Required. The parent in whose context the Deployments - are listed. The parent value is in the format: - 'projects/{project_id}/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.config_v1.services.config.pagers.ListDeploymentsAsyncPager: - 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, config.ListDeploymentsRequest): - request = config.ListDeploymentsRequest(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_deployments] - - # 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.ListDeploymentsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_deployment(self, - request: Optional[Union[config.GetDeploymentRequest, 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]]] = (), - ) -> config.Deployment: - r"""Gets details about a - [Deployment][google.cloud.config.v1.Deployment]. - - .. 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 config_v1 - - async def sample_get_deployment(): - # Create a client - client = config_v1.ConfigAsyncClient() - - # Initialize request argument(s) - request = config_v1.GetDeploymentRequest( - name="name_value", - ) - - # Make the request - response = await client.get_deployment(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.config_v1.types.GetDeploymentRequest, dict]]): - The request object. - name (:class:`str`): - Required. The name of the deployment. Format: - 'projects/{project_id}/locations/{location}/deployments/{deployment}'. - - 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.config_v1.types.Deployment: - A Deployment is a group of resources - and configs managed and provisioned by - Infra Manager. - - """ - # 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, config.GetDeploymentRequest): - request = config.GetDeploymentRequest(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_deployment] - - # 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_deployment(self, - request: Optional[Union[config.CreateDeploymentRequest, dict]] = None, - *, - parent: Optional[str] = None, - deployment: Optional[config.Deployment] = None, - deployment_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 [Deployment][google.cloud.config.v1.Deployment]. - - .. 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 config_v1 - - async def sample_create_deployment(): - # Create a client - client = config_v1.ConfigAsyncClient() - - # Initialize request argument(s) - deployment = config_v1.Deployment() - deployment.terraform_blueprint.gcs_source = "gcs_source_value" - - request = config_v1.CreateDeploymentRequest( - parent="parent_value", - deployment_id="deployment_id_value", - deployment=deployment, - ) - - # Make the request - operation = client.create_deployment(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.config_v1.types.CreateDeploymentRequest, dict]]): - The request object. - parent (:class:`str`): - Required. The parent in whose context the Deployment is - created. The parent value is in the format: - 'projects/{project_id}/locations/{location}'. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - deployment (:class:`google.cloud.config_v1.types.Deployment`): - Required. - [Deployment][google.cloud.config.v1.Deployment] resource - to be created. - - This corresponds to the ``deployment`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - deployment_id (:class:`str`): - Required. The Deployment ID. - This corresponds to the ``deployment_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.config_v1.types.Deployment` A Deployment is a group of resources and configs managed and provisioned by - Infra Manager. - - """ - # 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, deployment, deployment_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, config.CreateDeploymentRequest): - request = config.CreateDeploymentRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if deployment is not None: - request.deployment = deployment - if deployment_id is not None: - request.deployment_id = deployment_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_deployment] - - # 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, - config.Deployment, - metadata_type=config.OperationMetadata, - ) - - # Done; return the response. - return response - - async def update_deployment(self, - request: Optional[Union[config.UpdateDeploymentRequest, dict]] = None, - *, - deployment: Optional[config.Deployment] = 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 a [Deployment][google.cloud.config.v1.Deployment]. - - .. 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 config_v1 - - async def sample_update_deployment(): - # Create a client - client = config_v1.ConfigAsyncClient() - - # Initialize request argument(s) - deployment = config_v1.Deployment() - deployment.terraform_blueprint.gcs_source = "gcs_source_value" - - request = config_v1.UpdateDeploymentRequest( - deployment=deployment, - ) - - # Make the request - operation = client.update_deployment(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.config_v1.types.UpdateDeploymentRequest, dict]]): - The request object. - deployment (:class:`google.cloud.config_v1.types.Deployment`): - Required. - [Deployment][google.cloud.config.v1.Deployment] to - update. - - The deployment's ``name`` field is used to identify the - resource to be updated. Format: - ``projects/{project}/locations/{location}/deployments/{deployment}`` - - This corresponds to the ``deployment`` 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 - overwritten in the Deployment 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.config_v1.types.Deployment` A Deployment is a group of resources and configs managed and provisioned by - Infra Manager. - - """ - # 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 = [deployment, 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, config.UpdateDeploymentRequest): - request = config.UpdateDeploymentRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if deployment is not None: - request.deployment = deployment - 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_deployment] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("deployment.name", request.deployment.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, - config.Deployment, - metadata_type=config.OperationMetadata, - ) - - # Done; return the response. - return response - - async def delete_deployment(self, - request: Optional[Union[config.DeleteDeploymentRequest, 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 [Deployment][google.cloud.config.v1.Deployment]. - - .. 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 config_v1 - - async def sample_delete_deployment(): - # Create a client - client = config_v1.ConfigAsyncClient() - - # Initialize request argument(s) - request = config_v1.DeleteDeploymentRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_deployment(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.config_v1.types.DeleteDeploymentRequest, dict]]): - The request object. - name (:class:`str`): - Required. The name of the Deployment in the format: - 'projects/{project_id}/locations/{location}/deployments/{deployment}'. - - 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.config_v1.types.Deployment` A Deployment is a group of resources and configs managed and provisioned by - Infra Manager. - - """ - # 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, config.DeleteDeploymentRequest): - request = config.DeleteDeploymentRequest(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_deployment] - - # 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, - config.Deployment, - metadata_type=config.OperationMetadata, - ) - - # Done; return the response. - return response - - async def list_revisions(self, - request: Optional[Union[config.ListRevisionsRequest, 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.ListRevisionsAsyncPager: - r"""Lists [Revision][google.cloud.config.v1.Revision]s of a - deployment. - - .. 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 config_v1 - - async def sample_list_revisions(): - # Create a client - client = config_v1.ConfigAsyncClient() - - # Initialize request argument(s) - request = config_v1.ListRevisionsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_revisions(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.config_v1.types.ListRevisionsRequest, dict]]): - The request object. A request to list Revisions passed to - a 'ListRevisions' call. - parent (:class:`str`): - Required. The parent in whose context the Revisions are - listed. The parent value is in the format: - 'projects/{project_id}/locations/{location}/deployments/{deployment}'. - - 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.config_v1.services.config.pagers.ListRevisionsAsyncPager: - A response to a 'ListRevisions' call. - Contains a list of Revisions. - 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, config.ListRevisionsRequest): - request = config.ListRevisionsRequest(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_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.ListRevisionsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_revision(self, - request: Optional[Union[config.GetRevisionRequest, 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]]] = (), - ) -> config.Revision: - r"""Gets details about a - [Revision][google.cloud.config.v1.Revision]. - - .. 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 config_v1 - - async def sample_get_revision(): - # Create a client - client = config_v1.ConfigAsyncClient() - - # Initialize request argument(s) - request = config_v1.GetRevisionRequest( - name="name_value", - ) - - # Make the request - response = await client.get_revision(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.config_v1.types.GetRevisionRequest, dict]]): - The request object. A request to get a Revision from a - 'GetRevision' call. - name (:class:`str`): - Required. The name of the Revision in the format: - 'projects/{project_id}/locations/{location}/deployments/{deployment}/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.config_v1.types.Revision: - A child resource of a Deployment - generated by a 'CreateDeployment' or - 'UpdateDeployment' call. Each Revision - contains metadata pertaining to a - snapshot of a particular Deployment. - - """ - # 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, config.GetRevisionRequest): - request = config.GetRevisionRequest(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_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 get_resource(self, - request: Optional[Union[config.GetResourceRequest, 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]]] = (), - ) -> config.Resource: - r"""Gets details about a [Resource][google.cloud.config.v1.Resource] - deployed by Infra Manager. - - .. 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 config_v1 - - async def sample_get_resource(): - # Create a client - client = config_v1.ConfigAsyncClient() - - # Initialize request argument(s) - request = config_v1.GetResourceRequest( - name="name_value", - ) - - # Make the request - response = await client.get_resource(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.config_v1.types.GetResourceRequest, dict]]): - The request object. A request to get a Resource from a - 'GetResource' call. - name (:class:`str`): - Required. The name of the Resource in the format: - 'projects/{project_id}/locations/{location}/deployments/{deployment}/revisions/{revision}/resource/{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.config_v1.types.Resource: - Resource represents a Google Cloud - Platform resource actuated by IM. - Resources are child resources of - Revisions. - - """ - # 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, config.GetResourceRequest): - request = config.GetResourceRequest(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_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_resources(self, - request: Optional[Union[config.ListResourcesRequest, 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.ListResourcesAsyncPager: - r"""Lists [Resources][google.cloud.config.v1.Resource] in a given - revision. - - .. 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 config_v1 - - async def sample_list_resources(): - # Create a client - client = config_v1.ConfigAsyncClient() - - # Initialize request argument(s) - request = config_v1.ListResourcesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_resources(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.config_v1.types.ListResourcesRequest, dict]]): - The request object. A request to list Resources passed to - a 'ListResources' call. - parent (:class:`str`): - Required. The parent in whose context the Resources are - listed. The parent value is in the format: - 'projects/{project_id}/locations/{location}/deployments/{deployment}/revisions/{revision}'. - - 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.config_v1.services.config.pagers.ListResourcesAsyncPager: - A response to a 'ListResources' call. - Contains a list of 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, config.ListResourcesRequest): - request = config.ListResourcesRequest(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_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.ListResourcesAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def export_deployment_statefile(self, - request: Optional[Union[config.ExportDeploymentStatefileRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> config.Statefile: - r"""Exports Terraform state file from a given deployment. - - .. 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 config_v1 - - async def sample_export_deployment_statefile(): - # Create a client - client = config_v1.ConfigAsyncClient() - - # Initialize request argument(s) - request = config_v1.ExportDeploymentStatefileRequest( - parent="parent_value", - ) - - # Make the request - response = await client.export_deployment_statefile(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.config_v1.types.ExportDeploymentStatefileRequest, dict]]): - The request object. A request to export a state file - passed to a 'ExportDeploymentStatefile' - call. - 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.config_v1.types.Statefile: - Contains info about a Terraform state - file - - """ - # 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, config.ExportDeploymentStatefileRequest): - request = config.ExportDeploymentStatefileRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.export_deployment_statefile] - - # 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 export_revision_statefile(self, - request: Optional[Union[config.ExportRevisionStatefileRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> config.Statefile: - r"""Exports Terraform state file from a given revision. - - .. 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 config_v1 - - async def sample_export_revision_statefile(): - # Create a client - client = config_v1.ConfigAsyncClient() - - # Initialize request argument(s) - request = config_v1.ExportRevisionStatefileRequest( - parent="parent_value", - ) - - # Make the request - response = await client.export_revision_statefile(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.config_v1.types.ExportRevisionStatefileRequest, dict]]): - The request object. A request to export a state file - passed to a 'ExportRevisionStatefile' - call. - 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.config_v1.types.Statefile: - Contains info about a Terraform state - file - - """ - # 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, config.ExportRevisionStatefileRequest): - request = config.ExportRevisionStatefileRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.export_revision_statefile] - - # 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 import_statefile(self, - request: Optional[Union[config.ImportStatefileRequest, dict]] = None, - *, - parent: Optional[str] = None, - lock_id: Optional[int] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> config.Statefile: - r"""Imports Terraform state file in a given deployment. - The state file does not take effect until the Deployment - has been unlocked. - - .. 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 config_v1 - - async def sample_import_statefile(): - # Create a client - client = config_v1.ConfigAsyncClient() - - # Initialize request argument(s) - request = config_v1.ImportStatefileRequest( - parent="parent_value", - lock_id=725, - ) - - # Make the request - response = await client.import_statefile(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.config_v1.types.ImportStatefileRequest, dict]]): - The request object. A request to import a state file - passed to a 'ImportStatefile' call. - parent (:class:`str`): - Required. The parent in whose context the statefile is - listed. The parent value is in the format: - 'projects/{project_id}/locations/{location}/deployments/{deployment}'. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - lock_id (:class:`int`): - Required. Lock ID of the lock file to - verify that the user who is importing - the state file previously locked the - Deployment. - - This corresponds to the ``lock_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.config_v1.types.Statefile: - Contains info about a Terraform state - file - - """ - # 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, lock_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, config.ImportStatefileRequest): - request = config.ImportStatefileRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if lock_id is not None: - request.lock_id = lock_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.import_statefile] - - # 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 delete_statefile(self, - request: Optional[Union[config.DeleteStatefileRequest, 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 Terraform state file in a given deployment. - - .. 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 config_v1 - - async def sample_delete_statefile(): - # Create a client - client = config_v1.ConfigAsyncClient() - - # Initialize request argument(s) - request = config_v1.DeleteStatefileRequest( - name="name_value", - lock_id=725, - ) - - # Make the request - await client.delete_statefile(request=request) - - Args: - request (Optional[Union[google.cloud.config_v1.types.DeleteStatefileRequest, dict]]): - The request object. A request to delete a state file - passed to a 'DeleteStatefile' call. - name (:class:`str`): - Required. The name of the deployment in the format: - 'projects/{project_id}/locations/{location}/deployments/{deployment}'. - - 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, config.DeleteStatefileRequest): - request = config.DeleteStatefileRequest(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_statefile] - - # 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 lock_deployment(self, - request: Optional[Union[config.LockDeploymentRequest, 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"""Locks a deployment. - - .. 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 config_v1 - - async def sample_lock_deployment(): - # Create a client - client = config_v1.ConfigAsyncClient() - - # Initialize request argument(s) - request = config_v1.LockDeploymentRequest( - name="name_value", - ) - - # Make the request - operation = client.lock_deployment(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.config_v1.types.LockDeploymentRequest, dict]]): - The request object. A request to lock a deployment passed - to a 'LockDeployment' call. - name (:class:`str`): - Required. The name of the deployment in the format: - 'projects/{project_id}/locations/{location}/deployments/{deployment}'. - - 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.config_v1.types.Deployment` A Deployment is a group of resources and configs managed and provisioned by - Infra Manager. - - """ - # 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, config.LockDeploymentRequest): - request = config.LockDeploymentRequest(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.lock_deployment] - - # 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, - config.Deployment, - metadata_type=config.OperationMetadata, - ) - - # Done; return the response. - return response - - async def unlock_deployment(self, - request: Optional[Union[config.UnlockDeploymentRequest, dict]] = None, - *, - name: Optional[str] = None, - lock_id: Optional[int] = 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"""Unlocks a locked deployment. - - .. 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 config_v1 - - async def sample_unlock_deployment(): - # Create a client - client = config_v1.ConfigAsyncClient() - - # Initialize request argument(s) - request = config_v1.UnlockDeploymentRequest( - name="name_value", - lock_id=725, - ) - - # Make the request - operation = client.unlock_deployment(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.config_v1.types.UnlockDeploymentRequest, dict]]): - The request object. A request to unlock a state file - passed to a 'UnlockDeployment' call. - name (:class:`str`): - Required. The name of the deployment in the format: - 'projects/{project_id}/locations/{location}/deployments/{deployment}'. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - lock_id (:class:`int`): - Required. Lock ID of the lock file to - be unlocked. - - This corresponds to the ``lock_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.config_v1.types.Deployment` A Deployment is a group of resources and configs managed and provisioned by - Infra Manager. - - """ - # 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, lock_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, config.UnlockDeploymentRequest): - request = config.UnlockDeploymentRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if lock_id is not None: - request.lock_id = lock_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.unlock_deployment] - - # 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, - config.Deployment, - metadata_type=config.OperationMetadata, - ) - - # Done; return the response. - return response - - async def export_lock_info(self, - request: Optional[Union[config.ExportLockInfoRequest, 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]]] = (), - ) -> config.LockInfo: - r"""Exports the lock info on a locked deployment. - - .. 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 config_v1 - - async def sample_export_lock_info(): - # Create a client - client = config_v1.ConfigAsyncClient() - - # Initialize request argument(s) - request = config_v1.ExportLockInfoRequest( - name="name_value", - ) - - # Make the request - response = await client.export_lock_info(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.config_v1.types.ExportLockInfoRequest, dict]]): - The request object. A request to get a state file lock - info passed to a 'ExportLockInfo' call. - name (:class:`str`): - Required. The name of the deployment in the format: - 'projects/{project_id}/locations/{location}/deployments/{deployment}'. - - 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.config_v1.types.LockInfo: - Details about the lock which locked - the deployment. - - """ - # 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, config.ExportLockInfoRequest): - request = config.ExportLockInfoRequest(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.export_lock_info] - - # 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_preview(self, - request: Optional[Union[config.CreatePreviewRequest, dict]] = None, - *, - parent: Optional[str] = None, - preview: Optional[config.Preview] = 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 [Preview][google.cloud.config.v1.Preview]. - - .. 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 config_v1 - - async def sample_create_preview(): - # Create a client - client = config_v1.ConfigAsyncClient() - - # Initialize request argument(s) - preview = config_v1.Preview() - preview.terraform_blueprint.gcs_source = "gcs_source_value" - preview.service_account = "service_account_value" - - request = config_v1.CreatePreviewRequest( - parent="parent_value", - preview=preview, - ) - - # Make the request - operation = client.create_preview(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.config_v1.types.CreatePreviewRequest, dict]]): - The request object. A request to create a preview. - parent (:class:`str`): - Required. The parent in whose context the Preview is - created. The parent value is in the format: - 'projects/{project_id}/locations/{location}'. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - preview (:class:`google.cloud.config_v1.types.Preview`): - Required. [Preview][google.cloud.config.v1.Preview] - resource to be created. - - This corresponds to the ``preview`` 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.config_v1.types.Preview` A preview represents a set of actions Infra Manager would perform - to move the resources towards the desired state as - specified in the configuration. - - """ - # 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, preview] - 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, config.CreatePreviewRequest): - request = config.CreatePreviewRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if preview is not None: - request.preview = preview - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_preview] - - # 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, - config.Preview, - metadata_type=config.OperationMetadata, - ) - - # Done; return the response. - return response - - async def get_preview(self, - request: Optional[Union[config.GetPreviewRequest, 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]]] = (), - ) -> config.Preview: - r"""Gets details about a [Preview][google.cloud.config.v1.Preview]. - - .. 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 config_v1 - - async def sample_get_preview(): - # Create a client - client = config_v1.ConfigAsyncClient() - - # Initialize request argument(s) - request = config_v1.GetPreviewRequest( - name="name_value", - ) - - # Make the request - response = await client.get_preview(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.config_v1.types.GetPreviewRequest, dict]]): - The request object. A request to get details about a - preview. - name (:class:`str`): - Required. The name of the preview. Format: - 'projects/{project_id}/locations/{location}/previews/{preview}'. - - 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.config_v1.types.Preview: - A preview represents a set of actions - Infra Manager would perform to move the - resources towards the desired state as - specified in the configuration. - - """ - # 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, config.GetPreviewRequest): - request = config.GetPreviewRequest(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_preview] - - # 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_previews(self, - request: Optional[Union[config.ListPreviewsRequest, 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.ListPreviewsAsyncPager: - r"""Lists [Preview][google.cloud.config.v1.Preview]s 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 config_v1 - - async def sample_list_previews(): - # Create a client - client = config_v1.ConfigAsyncClient() - - # Initialize request argument(s) - request = config_v1.ListPreviewsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_previews(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.config_v1.types.ListPreviewsRequest, dict]]): - The request object. A request to list all previews for a - given project and location. - parent (:class:`str`): - Required. The parent in whose context the Previews are - listed. The parent value is in the format: - 'projects/{project_id}/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.config_v1.services.config.pagers.ListPreviewsAsyncPager: - A response to a ListPreviews call. Contains a list of - Previews. - - 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, config.ListPreviewsRequest): - request = config.ListPreviewsRequest(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_previews] - - # 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.ListPreviewsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_preview(self, - request: Optional[Union[config.DeletePreviewRequest, 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 [Preview][google.cloud.config.v1.Preview]. - - .. 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 config_v1 - - async def sample_delete_preview(): - # Create a client - client = config_v1.ConfigAsyncClient() - - # Initialize request argument(s) - request = config_v1.DeletePreviewRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_preview(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.config_v1.types.DeletePreviewRequest, dict]]): - The request object. A request to delete a preview. - name (:class:`str`): - Required. The name of the Preview in the format: - 'projects/{project_id}/locations/{location}/previews/{preview}'. - - 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.config_v1.types.Preview` A preview represents a set of actions Infra Manager would perform - to move the resources towards the desired state as - specified in the configuration. - - """ - # 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, config.DeletePreviewRequest): - request = config.DeletePreviewRequest(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_preview] - - # 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, - config.Preview, - metadata_type=config.OperationMetadata, - ) - - # Done; return the response. - return response - - async def export_preview_result(self, - request: Optional[Union[config.ExportPreviewResultRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> config.ExportPreviewResultResponse: - r"""Export [Preview][google.cloud.config.v1.Preview] results. - - .. 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 config_v1 - - async def sample_export_preview_result(): - # Create a client - client = config_v1.ConfigAsyncClient() - - # Initialize request argument(s) - request = config_v1.ExportPreviewResultRequest( - parent="parent_value", - ) - - # Make the request - response = await client.export_preview_result(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.config_v1.types.ExportPreviewResultRequest, dict]]): - The request object. A request to export preview results. - 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.config_v1.types.ExportPreviewResultResponse: - A response to ExportPreviewResult call. Contains preview - results. - - """ - # 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, config.ExportPreviewResultRequest): - request = config.ExportPreviewResultRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.export_preview_result] - - # 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 list_terraform_versions(self, - request: Optional[Union[config.ListTerraformVersionsRequest, 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.ListTerraformVersionsAsyncPager: - r"""Lists - [TerraformVersion][google.cloud.config.v1.TerraformVersion]s 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 config_v1 - - async def sample_list_terraform_versions(): - # Create a client - client = config_v1.ConfigAsyncClient() - - # Initialize request argument(s) - request = config_v1.ListTerraformVersionsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_terraform_versions(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.config_v1.types.ListTerraformVersionsRequest, dict]]): - The request object. The request message for the - ListTerraformVersions method. - parent (:class:`str`): - Required. The parent in whose context the - TerraformVersions are listed. The parent value is in the - format: 'projects/{project_id}/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.config_v1.services.config.pagers.ListTerraformVersionsAsyncPager: - The response message for the ListTerraformVersions - 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, config.ListTerraformVersionsRequest): - request = config.ListTerraformVersionsRequest(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_terraform_versions] - - # 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.ListTerraformVersionsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_terraform_version(self, - request: Optional[Union[config.GetTerraformVersionRequest, 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]]] = (), - ) -> config.TerraformVersion: - r"""Gets details about a - [TerraformVersion][google.cloud.config.v1.TerraformVersion]. - - .. 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 config_v1 - - async def sample_get_terraform_version(): - # Create a client - client = config_v1.ConfigAsyncClient() - - # Initialize request argument(s) - request = config_v1.GetTerraformVersionRequest( - name="name_value", - ) - - # Make the request - response = await client.get_terraform_version(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.config_v1.types.GetTerraformVersionRequest, dict]]): - The request object. The request message for the - GetTerraformVersion method. - name (:class:`str`): - Required. The name of the TerraformVersion. Format: - 'projects/{project_id}/locations/{location}/terraformVersions/{terraform_version}' - - 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.config_v1.types.TerraformVersion: - A TerraformVersion represents the - support state the corresponding - Terraform version. - - """ - # 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, config.GetTerraformVersionRequest): - request = config.GetTerraformVersionRequest(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_terraform_version] - - # 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_resource_changes(self, - request: Optional[Union[config.ListResourceChangesRequest, 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.ListResourceChangesAsyncPager: - r"""Lists ResourceChanges for a given preview. - - .. 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 config_v1 - - async def sample_list_resource_changes(): - # Create a client - client = config_v1.ConfigAsyncClient() - - # Initialize request argument(s) - request = config_v1.ListResourceChangesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_resource_changes(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.config_v1.types.ListResourceChangesRequest, dict]]): - The request object. The request message for the - ListResourceChanges method. - parent (:class:`str`): - Required. The parent in whose context the - ResourceChanges are listed. The parent value is in the - format: - 'projects/{project_id}/locations/{location}/previews/{preview}'. - - 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.config_v1.services.config.pagers.ListResourceChangesAsyncPager: - A response to a 'ListResourceChanges' - call. Contains a list of - ResourceChanges. - - 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, config.ListResourceChangesRequest): - request = config.ListResourceChangesRequest(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_changes] - - # 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.ListResourceChangesAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_resource_change(self, - request: Optional[Union[config.GetResourceChangeRequest, 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]]] = (), - ) -> config.ResourceChange: - r"""Get a ResourceChange for a given preview. - - .. 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 config_v1 - - async def sample_get_resource_change(): - # Create a client - client = config_v1.ConfigAsyncClient() - - # Initialize request argument(s) - request = config_v1.GetResourceChangeRequest( - name="name_value", - ) - - # Make the request - response = await client.get_resource_change(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.config_v1.types.GetResourceChangeRequest, dict]]): - The request object. The request message for the - GetResourceChange method. - name (:class:`str`): - Required. The name of the resource change to retrieve. - Format: - 'projects/{project_id}/locations/{location}/previews/{preview}/resourceChanges/{resource_change}'. - - 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.config_v1.types.ResourceChange: - A resource change represents a change - to a resource in the state file. - - """ - # 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, config.GetResourceChangeRequest): - request = config.GetResourceChangeRequest(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_resource_change] - - # 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_resource_drifts(self, - request: Optional[Union[config.ListResourceDriftsRequest, 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.ListResourceDriftsAsyncPager: - r"""List ResourceDrifts for a given preview. - - .. 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 config_v1 - - async def sample_list_resource_drifts(): - # Create a client - client = config_v1.ConfigAsyncClient() - - # Initialize request argument(s) - request = config_v1.ListResourceDriftsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_resource_drifts(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.config_v1.types.ListResourceDriftsRequest, dict]]): - The request object. The request message for the - ListResourceDrifts method. - parent (:class:`str`): - Required. The parent in whose context the ResourceDrifts - are listed. The parent value is in the format: - 'projects/{project_id}/locations/{location}/previews/{preview}'. - - 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.config_v1.services.config.pagers.ListResourceDriftsAsyncPager: - A response to a 'ListResourceDrifts' - call. Contains a list of ResourceDrifts. - 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, config.ListResourceDriftsRequest): - request = config.ListResourceDriftsRequest(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_drifts] - - # 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.ListResourceDriftsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_resource_drift(self, - request: Optional[Union[config.GetResourceDriftRequest, 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]]] = (), - ) -> config.ResourceDrift: - r"""Get a ResourceDrift for a given preview. - - .. 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 config_v1 - - async def sample_get_resource_drift(): - # Create a client - client = config_v1.ConfigAsyncClient() - - # Initialize request argument(s) - request = config_v1.GetResourceDriftRequest( - name="name_value", - ) - - # Make the request - response = await client.get_resource_drift(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.config_v1.types.GetResourceDriftRequest, dict]]): - The request object. The request message for the - GetResourceDrift method. - name (:class:`str`): - Required. The name of the resource drift to retrieve. - Format: - 'projects/{project_id}/locations/{location}/previews/{preview}/resourceDrifts/{resource_drift}'. - - 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.config_v1.types.ResourceDrift: - A resource drift represents a drift - to a resource in the state file. - - """ - # 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, config.GetResourceDriftRequest): - request = config.GetResourceDriftRequest(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_resource_drift] - - # 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_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = 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 isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**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.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_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = 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 isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**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.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 delete_operation( - self, - request: Optional[operations_pb2.DeleteOperationRequest] = 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 isinstance(request, dict): - request = operations_pb2.DeleteOperationRequest(**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.name),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - async def cancel_operation( - self, - request: Optional[operations_pb2.CancelOperationRequest] = 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 isinstance(request, dict): - request = operations_pb2.CancelOperationRequest(**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.name),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - async def set_iam_policy( - self, - request: Optional[iam_policy_pb2.SetIamPolicyRequest] = 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 isinstance(request, dict): - request = iam_policy_pb2.SetIamPolicyRequest(**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.resource),)), - ) - - # 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_iam_policy( - self, - request: Optional[iam_policy_pb2.GetIamPolicyRequest] = 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 isinstance(request, dict): - request = iam_policy_pb2.GetIamPolicyRequest(**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.resource),)), - ) - - # 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 test_iam_permissions( - self, - request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = 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 isinstance(request, dict): - request = iam_policy_pb2.TestIamPermissionsRequest(**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.resource),)), - ) - - # 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_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = 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 isinstance(request, dict): - request = locations_pb2.GetLocationRequest(**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.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_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = 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 isinstance(request, dict): - request = locations_pb2.ListLocationsRequest(**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.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 __aenter__(self) -> "ConfigAsyncClient": - 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__) - -if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER - DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ - - -__all__ = ( - "ConfigAsyncClient", -) diff --git a/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/client.py b/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/client.py deleted file mode 100644 index f8d0c7523492..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/client.py +++ /dev/null @@ -1,4436 +0,0 @@ -# -*- 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. -# -from collections import OrderedDict -from http import HTTPStatus -import json -import logging as std_logging -import os -import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast -import warnings - -from google.cloud.config_v1 import gapic_version as package_version - -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.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore -import google.protobuf - -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.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.config_v1.services.config import pagers -from google.cloud.config_v1.types import config -from google.cloud.location import locations_pb2 # type: ignore -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore -from .transports.base import ConfigTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import ConfigGrpcTransport -from .transports.grpc_asyncio import ConfigGrpcAsyncIOTransport -from .transports.rest import ConfigRestTransport - - -class ConfigClientMeta(type): - """Metaclass for the Config 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[ConfigTransport]] - _transport_registry["grpc"] = ConfigGrpcTransport - _transport_registry["grpc_asyncio"] = ConfigGrpcAsyncIOTransport - _transport_registry["rest"] = ConfigRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[ConfigTransport]: - """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 ConfigClient(metaclass=ConfigClientMeta): - """Infrastructure Manager is a managed service that automates - the deployment and management of Google Cloud infrastructure - resources. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = "config.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - _DEFAULT_ENDPOINT_TEMPLATE = "config.{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: - ConfigClient: 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: - ConfigClient: 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) -> ConfigTransport: - """Returns the transport used by the client instance. - - Returns: - ConfigTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def deployment_path(project: str,location: str,deployment: str,) -> str: - """Returns a fully-qualified deployment string.""" - return "projects/{project}/locations/{location}/deployments/{deployment}".format(project=project, location=location, deployment=deployment, ) - - @staticmethod - def parse_deployment_path(path: str) -> Dict[str,str]: - """Parses a deployment path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/deployments/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def preview_path(project: str,location: str,preview: str,) -> str: - """Returns a fully-qualified preview string.""" - return "projects/{project}/locations/{location}/previews/{preview}".format(project=project, location=location, preview=preview, ) - - @staticmethod - def parse_preview_path(path: str) -> Dict[str,str]: - """Parses a preview path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/previews/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def resource_path(project: str,location: str,deployment: str,revision: str,resource: str,) -> str: - """Returns a fully-qualified resource string.""" - return "projects/{project}/locations/{location}/deployments/{deployment}/revisions/{revision}/resources/{resource}".format(project=project, location=location, deployment=deployment, revision=revision, resource=resource, ) - - @staticmethod - def parse_resource_path(path: str) -> Dict[str,str]: - """Parses a resource path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/deployments/(?P.+?)/revisions/(?P.+?)/resources/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def resource_change_path(project: str,location: str,preview: str,resource_change: str,) -> str: - """Returns a fully-qualified resource_change string.""" - return "projects/{project}/locations/{location}/previews/{preview}/resourceChanges/{resource_change}".format(project=project, location=location, preview=preview, resource_change=resource_change, ) - - @staticmethod - def parse_resource_change_path(path: str) -> Dict[str,str]: - """Parses a resource_change path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/previews/(?P.+?)/resourceChanges/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def resource_drift_path(project: str,location: str,preview: str,resource_drift: str,) -> str: - """Returns a fully-qualified resource_drift string.""" - return "projects/{project}/locations/{location}/previews/{preview}/resourceDrifts/{resource_drift}".format(project=project, location=location, preview=preview, resource_drift=resource_drift, ) - - @staticmethod - def parse_resource_drift_path(path: str) -> Dict[str,str]: - """Parses a resource_drift path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/previews/(?P.+?)/resourceDrifts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def revision_path(project: str,location: str,deployment: str,revision: str,) -> str: - """Returns a fully-qualified revision string.""" - return "projects/{project}/locations/{location}/deployments/{deployment}/revisions/{revision}".format(project=project, location=location, deployment=deployment, revision=revision, ) - - @staticmethod - def parse_revision_path(path: str) -> Dict[str,str]: - """Parses a revision path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/deployments/(?P.+?)/revisions/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def service_account_path(project: str,service_account: str,) -> str: - """Returns a fully-qualified service_account string.""" - return "projects/{project}/serviceAccounts/{service_account}".format(project=project, service_account=service_account, ) - - @staticmethod - def parse_service_account_path(path: str) -> Dict[str,str]: - """Parses a service_account path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/serviceAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def terraform_version_path(project: str,location: str,terraform_version: str,) -> str: - """Returns a fully-qualified terraform_version string.""" - return "projects/{project}/locations/{location}/terraformVersions/{terraform_version}".format(project=project, location=location, terraform_version=terraform_version, ) - - @staticmethod - def parse_terraform_version_path(path: str) -> Dict[str,str]: - """Parses a terraform_version path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/terraformVersions/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def worker_pool_path(project: str,location: str,worker_pool: str,) -> str: - """Returns a fully-qualified worker_pool string.""" - return "projects/{project}/locations/{location}/workerPools/{worker_pool}".format(project=project, location=location, worker_pool=worker_pool, ) - - @staticmethod - def parse_worker_pool_path(path: str) -> Dict[str,str]: - """Parses a worker_pool path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/workerPools/(?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 = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - 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 == "true": - 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 - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - @staticmethod - 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 = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() - universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - 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 == "true", use_mtls_endpoint, universe_domain_env - - @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 - - @staticmethod - def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint): - """Return the API endpoint used by the client. - - Args: - api_override (str): The API endpoint override. If specified, this is always - the return value of this function and the other arguments are not used. - client_cert_source (bytes): The client certificate source used by the client. - universe_domain (str): The universe domain used by the client. - use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. - Possible values are "always", "auto", or "never". - - Returns: - str: The API endpoint to be used by the client. - """ - if api_override is not None: - api_endpoint = api_override - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - _default_universe = ConfigClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = ConfigClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = ConfigClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=universe_domain) - return api_endpoint - - @staticmethod - def _get_universe_domain(client_universe_domain: Optional[str], universe_domain_env: Optional[str]) -> str: - """Return the universe domain used by the client. - - Args: - client_universe_domain (Optional[str]): The universe domain configured via the client options. - universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. - - Returns: - str: The universe domain to be used by the client. - - Raises: - ValueError: If the universe domain is an empty string. - """ - universe_domain = ConfigClient._DEFAULT_UNIVERSE - if client_universe_domain is not None: - universe_domain = client_universe_domain - elif universe_domain_env is not None: - universe_domain = universe_domain_env - if len(universe_domain.strip()) == 0: - raise ValueError("Universe Domain cannot be an empty string.") - return universe_domain - - 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): - """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, ConfigTransport, Callable[..., ConfigTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the config 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,ConfigTransport,Callable[..., ConfigTransport]]]): - 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 ConfigTransport 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 = ConfigClient._read_environment_variables() - self._client_cert_source = ConfigClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = ConfigClient._get_universe_domain(universe_domain_opt, self._universe_domain_env) - self._api_endpoint = None # 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, ConfigTransport) - if transport_provided: - # transport is a ConfigTransport 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(ConfigTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - ConfigClient._get_api_endpoint( - self._client_options.api_endpoint, - self._client_cert_source, - self._universe_domain, - self._use_mtls_endpoint)) - - 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[ConfigTransport], Callable[..., ConfigTransport]] = ( - ConfigClient.get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., ConfigTransport], 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.config_v1.ConfigClient`.", - extra = { - "serviceName": "google.cloud.config.v1.Config", - "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.config.v1.Config", - "credentialsType": None, - } - ) - - def list_deployments(self, - request: Optional[Union[config.ListDeploymentsRequest, 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.ListDeploymentsPager: - r"""Lists [Deployment][google.cloud.config.v1.Deployment]s 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 config_v1 - - def sample_list_deployments(): - # Create a client - client = config_v1.ConfigClient() - - # Initialize request argument(s) - request = config_v1.ListDeploymentsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_deployments(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.config_v1.types.ListDeploymentsRequest, dict]): - The request object. - parent (str): - Required. The parent in whose context the Deployments - are listed. The parent value is in the format: - 'projects/{project_id}/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.config_v1.services.config.pagers.ListDeploymentsPager: - 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, config.ListDeploymentsRequest): - request = config.ListDeploymentsRequest(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_deployments] - - # 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.ListDeploymentsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_deployment(self, - request: Optional[Union[config.GetDeploymentRequest, 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]]] = (), - ) -> config.Deployment: - r"""Gets details about a - [Deployment][google.cloud.config.v1.Deployment]. - - .. 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 config_v1 - - def sample_get_deployment(): - # Create a client - client = config_v1.ConfigClient() - - # Initialize request argument(s) - request = config_v1.GetDeploymentRequest( - name="name_value", - ) - - # Make the request - response = client.get_deployment(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.config_v1.types.GetDeploymentRequest, dict]): - The request object. - name (str): - Required. The name of the deployment. Format: - 'projects/{project_id}/locations/{location}/deployments/{deployment}'. - - 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.config_v1.types.Deployment: - A Deployment is a group of resources - and configs managed and provisioned by - Infra Manager. - - """ - # 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, config.GetDeploymentRequest): - request = config.GetDeploymentRequest(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_deployment] - - # 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_deployment(self, - request: Optional[Union[config.CreateDeploymentRequest, dict]] = None, - *, - parent: Optional[str] = None, - deployment: Optional[config.Deployment] = None, - deployment_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 [Deployment][google.cloud.config.v1.Deployment]. - - .. 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 config_v1 - - def sample_create_deployment(): - # Create a client - client = config_v1.ConfigClient() - - # Initialize request argument(s) - deployment = config_v1.Deployment() - deployment.terraform_blueprint.gcs_source = "gcs_source_value" - - request = config_v1.CreateDeploymentRequest( - parent="parent_value", - deployment_id="deployment_id_value", - deployment=deployment, - ) - - # Make the request - operation = client.create_deployment(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.config_v1.types.CreateDeploymentRequest, dict]): - The request object. - parent (str): - Required. The parent in whose context the Deployment is - created. The parent value is in the format: - 'projects/{project_id}/locations/{location}'. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - deployment (google.cloud.config_v1.types.Deployment): - Required. - [Deployment][google.cloud.config.v1.Deployment] resource - to be created. - - This corresponds to the ``deployment`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - deployment_id (str): - Required. The Deployment ID. - This corresponds to the ``deployment_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.config_v1.types.Deployment` A Deployment is a group of resources and configs managed and provisioned by - Infra Manager. - - """ - # 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, deployment, deployment_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, config.CreateDeploymentRequest): - request = config.CreateDeploymentRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if deployment is not None: - request.deployment = deployment - if deployment_id is not None: - request.deployment_id = deployment_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_deployment] - - # 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, - config.Deployment, - metadata_type=config.OperationMetadata, - ) - - # Done; return the response. - return response - - def update_deployment(self, - request: Optional[Union[config.UpdateDeploymentRequest, dict]] = None, - *, - deployment: Optional[config.Deployment] = 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 a [Deployment][google.cloud.config.v1.Deployment]. - - .. 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 config_v1 - - def sample_update_deployment(): - # Create a client - client = config_v1.ConfigClient() - - # Initialize request argument(s) - deployment = config_v1.Deployment() - deployment.terraform_blueprint.gcs_source = "gcs_source_value" - - request = config_v1.UpdateDeploymentRequest( - deployment=deployment, - ) - - # Make the request - operation = client.update_deployment(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.config_v1.types.UpdateDeploymentRequest, dict]): - The request object. - deployment (google.cloud.config_v1.types.Deployment): - Required. - [Deployment][google.cloud.config.v1.Deployment] to - update. - - The deployment's ``name`` field is used to identify the - resource to be updated. Format: - ``projects/{project}/locations/{location}/deployments/{deployment}`` - - This corresponds to the ``deployment`` 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 - overwritten in the Deployment 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.config_v1.types.Deployment` A Deployment is a group of resources and configs managed and provisioned by - Infra Manager. - - """ - # 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 = [deployment, 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, config.UpdateDeploymentRequest): - request = config.UpdateDeploymentRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if deployment is not None: - request.deployment = deployment - 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_deployment] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("deployment.name", request.deployment.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, - config.Deployment, - metadata_type=config.OperationMetadata, - ) - - # Done; return the response. - return response - - def delete_deployment(self, - request: Optional[Union[config.DeleteDeploymentRequest, 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 [Deployment][google.cloud.config.v1.Deployment]. - - .. 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 config_v1 - - def sample_delete_deployment(): - # Create a client - client = config_v1.ConfigClient() - - # Initialize request argument(s) - request = config_v1.DeleteDeploymentRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_deployment(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.config_v1.types.DeleteDeploymentRequest, dict]): - The request object. - name (str): - Required. The name of the Deployment in the format: - 'projects/{project_id}/locations/{location}/deployments/{deployment}'. - - 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.config_v1.types.Deployment` A Deployment is a group of resources and configs managed and provisioned by - Infra Manager. - - """ - # 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, config.DeleteDeploymentRequest): - request = config.DeleteDeploymentRequest(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_deployment] - - # 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, - config.Deployment, - metadata_type=config.OperationMetadata, - ) - - # Done; return the response. - return response - - def list_revisions(self, - request: Optional[Union[config.ListRevisionsRequest, 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.ListRevisionsPager: - r"""Lists [Revision][google.cloud.config.v1.Revision]s of a - deployment. - - .. 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 config_v1 - - def sample_list_revisions(): - # Create a client - client = config_v1.ConfigClient() - - # Initialize request argument(s) - request = config_v1.ListRevisionsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_revisions(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.config_v1.types.ListRevisionsRequest, dict]): - The request object. A request to list Revisions passed to - a 'ListRevisions' call. - parent (str): - Required. The parent in whose context the Revisions are - listed. The parent value is in the format: - 'projects/{project_id}/locations/{location}/deployments/{deployment}'. - - 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.config_v1.services.config.pagers.ListRevisionsPager: - A response to a 'ListRevisions' call. - Contains a list of Revisions. - 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, config.ListRevisionsRequest): - request = config.ListRevisionsRequest(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_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.ListRevisionsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_revision(self, - request: Optional[Union[config.GetRevisionRequest, 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]]] = (), - ) -> config.Revision: - r"""Gets details about a - [Revision][google.cloud.config.v1.Revision]. - - .. 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 config_v1 - - def sample_get_revision(): - # Create a client - client = config_v1.ConfigClient() - - # Initialize request argument(s) - request = config_v1.GetRevisionRequest( - name="name_value", - ) - - # Make the request - response = client.get_revision(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.config_v1.types.GetRevisionRequest, dict]): - The request object. A request to get a Revision from a - 'GetRevision' call. - name (str): - Required. The name of the Revision in the format: - 'projects/{project_id}/locations/{location}/deployments/{deployment}/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.config_v1.types.Revision: - A child resource of a Deployment - generated by a 'CreateDeployment' or - 'UpdateDeployment' call. Each Revision - contains metadata pertaining to a - snapshot of a particular Deployment. - - """ - # 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, config.GetRevisionRequest): - request = config.GetRevisionRequest(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_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 get_resource(self, - request: Optional[Union[config.GetResourceRequest, 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]]] = (), - ) -> config.Resource: - r"""Gets details about a [Resource][google.cloud.config.v1.Resource] - deployed by Infra Manager. - - .. 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 config_v1 - - def sample_get_resource(): - # Create a client - client = config_v1.ConfigClient() - - # Initialize request argument(s) - request = config_v1.GetResourceRequest( - name="name_value", - ) - - # Make the request - response = client.get_resource(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.config_v1.types.GetResourceRequest, dict]): - The request object. A request to get a Resource from a - 'GetResource' call. - name (str): - Required. The name of the Resource in the format: - 'projects/{project_id}/locations/{location}/deployments/{deployment}/revisions/{revision}/resource/{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.config_v1.types.Resource: - Resource represents a Google Cloud - Platform resource actuated by IM. - Resources are child resources of - Revisions. - - """ - # 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, config.GetResourceRequest): - request = config.GetResourceRequest(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_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_resources(self, - request: Optional[Union[config.ListResourcesRequest, 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.ListResourcesPager: - r"""Lists [Resources][google.cloud.config.v1.Resource] in a given - revision. - - .. 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 config_v1 - - def sample_list_resources(): - # Create a client - client = config_v1.ConfigClient() - - # Initialize request argument(s) - request = config_v1.ListResourcesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_resources(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.config_v1.types.ListResourcesRequest, dict]): - The request object. A request to list Resources passed to - a 'ListResources' call. - parent (str): - Required. The parent in whose context the Resources are - listed. The parent value is in the format: - 'projects/{project_id}/locations/{location}/deployments/{deployment}/revisions/{revision}'. - - 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.config_v1.services.config.pagers.ListResourcesPager: - A response to a 'ListResources' call. - Contains a list of 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, config.ListResourcesRequest): - request = config.ListResourcesRequest(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_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.ListResourcesPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def export_deployment_statefile(self, - request: Optional[Union[config.ExportDeploymentStatefileRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> config.Statefile: - r"""Exports Terraform state file from a given deployment. - - .. 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 config_v1 - - def sample_export_deployment_statefile(): - # Create a client - client = config_v1.ConfigClient() - - # Initialize request argument(s) - request = config_v1.ExportDeploymentStatefileRequest( - parent="parent_value", - ) - - # Make the request - response = client.export_deployment_statefile(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.config_v1.types.ExportDeploymentStatefileRequest, dict]): - The request object. A request to export a state file - passed to a 'ExportDeploymentStatefile' - call. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each 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.config_v1.types.Statefile: - Contains info about a Terraform state - file - - """ - # 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, config.ExportDeploymentStatefileRequest): - request = config.ExportDeploymentStatefileRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.export_deployment_statefile] - - # 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 export_revision_statefile(self, - request: Optional[Union[config.ExportRevisionStatefileRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> config.Statefile: - r"""Exports Terraform state file from a given revision. - - .. 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 config_v1 - - def sample_export_revision_statefile(): - # Create a client - client = config_v1.ConfigClient() - - # Initialize request argument(s) - request = config_v1.ExportRevisionStatefileRequest( - parent="parent_value", - ) - - # Make the request - response = client.export_revision_statefile(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.config_v1.types.ExportRevisionStatefileRequest, dict]): - The request object. A request to export a state file - passed to a 'ExportRevisionStatefile' - call. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each 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.config_v1.types.Statefile: - Contains info about a Terraform state - file - - """ - # 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, config.ExportRevisionStatefileRequest): - request = config.ExportRevisionStatefileRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.export_revision_statefile] - - # 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 import_statefile(self, - request: Optional[Union[config.ImportStatefileRequest, dict]] = None, - *, - parent: Optional[str] = None, - lock_id: Optional[int] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> config.Statefile: - r"""Imports Terraform state file in a given deployment. - The state file does not take effect until the Deployment - has been unlocked. - - .. 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 config_v1 - - def sample_import_statefile(): - # Create a client - client = config_v1.ConfigClient() - - # Initialize request argument(s) - request = config_v1.ImportStatefileRequest( - parent="parent_value", - lock_id=725, - ) - - # Make the request - response = client.import_statefile(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.config_v1.types.ImportStatefileRequest, dict]): - The request object. A request to import a state file - passed to a 'ImportStatefile' call. - parent (str): - Required. The parent in whose context the statefile is - listed. The parent value is in the format: - 'projects/{project_id}/locations/{location}/deployments/{deployment}'. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - lock_id (int): - Required. Lock ID of the lock file to - verify that the user who is importing - the state file previously locked the - Deployment. - - This corresponds to the ``lock_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.config_v1.types.Statefile: - Contains info about a Terraform state - file - - """ - # 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, lock_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, config.ImportStatefileRequest): - request = config.ImportStatefileRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if lock_id is not None: - request.lock_id = lock_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.import_statefile] - - # 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 delete_statefile(self, - request: Optional[Union[config.DeleteStatefileRequest, 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 Terraform state file in a given deployment. - - .. 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 config_v1 - - def sample_delete_statefile(): - # Create a client - client = config_v1.ConfigClient() - - # Initialize request argument(s) - request = config_v1.DeleteStatefileRequest( - name="name_value", - lock_id=725, - ) - - # Make the request - client.delete_statefile(request=request) - - Args: - request (Union[google.cloud.config_v1.types.DeleteStatefileRequest, dict]): - The request object. A request to delete a state file - passed to a 'DeleteStatefile' call. - name (str): - Required. The name of the deployment in the format: - 'projects/{project_id}/locations/{location}/deployments/{deployment}'. - - 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, config.DeleteStatefileRequest): - request = config.DeleteStatefileRequest(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_statefile] - - # 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 lock_deployment(self, - request: Optional[Union[config.LockDeploymentRequest, 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"""Locks a deployment. - - .. 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 config_v1 - - def sample_lock_deployment(): - # Create a client - client = config_v1.ConfigClient() - - # Initialize request argument(s) - request = config_v1.LockDeploymentRequest( - name="name_value", - ) - - # Make the request - operation = client.lock_deployment(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.config_v1.types.LockDeploymentRequest, dict]): - The request object. A request to lock a deployment passed - to a 'LockDeployment' call. - name (str): - Required. The name of the deployment in the format: - 'projects/{project_id}/locations/{location}/deployments/{deployment}'. - - 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.config_v1.types.Deployment` A Deployment is a group of resources and configs managed and provisioned by - Infra Manager. - - """ - # 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, config.LockDeploymentRequest): - request = config.LockDeploymentRequest(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.lock_deployment] - - # 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, - config.Deployment, - metadata_type=config.OperationMetadata, - ) - - # Done; return the response. - return response - - def unlock_deployment(self, - request: Optional[Union[config.UnlockDeploymentRequest, dict]] = None, - *, - name: Optional[str] = None, - lock_id: Optional[int] = 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"""Unlocks a locked deployment. - - .. 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 config_v1 - - def sample_unlock_deployment(): - # Create a client - client = config_v1.ConfigClient() - - # Initialize request argument(s) - request = config_v1.UnlockDeploymentRequest( - name="name_value", - lock_id=725, - ) - - # Make the request - operation = client.unlock_deployment(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.config_v1.types.UnlockDeploymentRequest, dict]): - The request object. A request to unlock a state file - passed to a 'UnlockDeployment' call. - name (str): - Required. The name of the deployment in the format: - 'projects/{project_id}/locations/{location}/deployments/{deployment}'. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - lock_id (int): - Required. Lock ID of the lock file to - be unlocked. - - This corresponds to the ``lock_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.config_v1.types.Deployment` A Deployment is a group of resources and configs managed and provisioned by - Infra Manager. - - """ - # 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, lock_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, config.UnlockDeploymentRequest): - request = config.UnlockDeploymentRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if lock_id is not None: - request.lock_id = lock_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.unlock_deployment] - - # 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, - config.Deployment, - metadata_type=config.OperationMetadata, - ) - - # Done; return the response. - return response - - def export_lock_info(self, - request: Optional[Union[config.ExportLockInfoRequest, 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]]] = (), - ) -> config.LockInfo: - r"""Exports the lock info on a locked deployment. - - .. 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 config_v1 - - def sample_export_lock_info(): - # Create a client - client = config_v1.ConfigClient() - - # Initialize request argument(s) - request = config_v1.ExportLockInfoRequest( - name="name_value", - ) - - # Make the request - response = client.export_lock_info(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.config_v1.types.ExportLockInfoRequest, dict]): - The request object. A request to get a state file lock - info passed to a 'ExportLockInfo' call. - name (str): - Required. The name of the deployment in the format: - 'projects/{project_id}/locations/{location}/deployments/{deployment}'. - - 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.config_v1.types.LockInfo: - Details about the lock which locked - the deployment. - - """ - # 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, config.ExportLockInfoRequest): - request = config.ExportLockInfoRequest(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.export_lock_info] - - # 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_preview(self, - request: Optional[Union[config.CreatePreviewRequest, dict]] = None, - *, - parent: Optional[str] = None, - preview: Optional[config.Preview] = 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 [Preview][google.cloud.config.v1.Preview]. - - .. 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 config_v1 - - def sample_create_preview(): - # Create a client - client = config_v1.ConfigClient() - - # Initialize request argument(s) - preview = config_v1.Preview() - preview.terraform_blueprint.gcs_source = "gcs_source_value" - preview.service_account = "service_account_value" - - request = config_v1.CreatePreviewRequest( - parent="parent_value", - preview=preview, - ) - - # Make the request - operation = client.create_preview(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.config_v1.types.CreatePreviewRequest, dict]): - The request object. A request to create a preview. - parent (str): - Required. The parent in whose context the Preview is - created. The parent value is in the format: - 'projects/{project_id}/locations/{location}'. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - preview (google.cloud.config_v1.types.Preview): - Required. [Preview][google.cloud.config.v1.Preview] - resource to be created. - - This corresponds to the ``preview`` 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.config_v1.types.Preview` A preview represents a set of actions Infra Manager would perform - to move the resources towards the desired state as - specified in the configuration. - - """ - # 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, preview] - 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, config.CreatePreviewRequest): - request = config.CreatePreviewRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if preview is not None: - request.preview = preview - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_preview] - - # 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, - config.Preview, - metadata_type=config.OperationMetadata, - ) - - # Done; return the response. - return response - - def get_preview(self, - request: Optional[Union[config.GetPreviewRequest, 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]]] = (), - ) -> config.Preview: - r"""Gets details about a [Preview][google.cloud.config.v1.Preview]. - - .. 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 config_v1 - - def sample_get_preview(): - # Create a client - client = config_v1.ConfigClient() - - # Initialize request argument(s) - request = config_v1.GetPreviewRequest( - name="name_value", - ) - - # Make the request - response = client.get_preview(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.config_v1.types.GetPreviewRequest, dict]): - The request object. A request to get details about a - preview. - name (str): - Required. The name of the preview. Format: - 'projects/{project_id}/locations/{location}/previews/{preview}'. - - 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.config_v1.types.Preview: - A preview represents a set of actions - Infra Manager would perform to move the - resources towards the desired state as - specified in the configuration. - - """ - # 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, config.GetPreviewRequest): - request = config.GetPreviewRequest(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_preview] - - # 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_previews(self, - request: Optional[Union[config.ListPreviewsRequest, 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.ListPreviewsPager: - r"""Lists [Preview][google.cloud.config.v1.Preview]s 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 config_v1 - - def sample_list_previews(): - # Create a client - client = config_v1.ConfigClient() - - # Initialize request argument(s) - request = config_v1.ListPreviewsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_previews(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.config_v1.types.ListPreviewsRequest, dict]): - The request object. A request to list all previews for a - given project and location. - parent (str): - Required. The parent in whose context the Previews are - listed. The parent value is in the format: - 'projects/{project_id}/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.config_v1.services.config.pagers.ListPreviewsPager: - A response to a ListPreviews call. Contains a list of - Previews. - - 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, config.ListPreviewsRequest): - request = config.ListPreviewsRequest(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_previews] - - # 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.ListPreviewsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_preview(self, - request: Optional[Union[config.DeletePreviewRequest, 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 [Preview][google.cloud.config.v1.Preview]. - - .. 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 config_v1 - - def sample_delete_preview(): - # Create a client - client = config_v1.ConfigClient() - - # Initialize request argument(s) - request = config_v1.DeletePreviewRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_preview(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.config_v1.types.DeletePreviewRequest, dict]): - The request object. A request to delete a preview. - name (str): - Required. The name of the Preview in the format: - 'projects/{project_id}/locations/{location}/previews/{preview}'. - - 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.config_v1.types.Preview` A preview represents a set of actions Infra Manager would perform - to move the resources towards the desired state as - specified in the configuration. - - """ - # 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, config.DeletePreviewRequest): - request = config.DeletePreviewRequest(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_preview] - - # 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, - config.Preview, - metadata_type=config.OperationMetadata, - ) - - # Done; return the response. - return response - - def export_preview_result(self, - request: Optional[Union[config.ExportPreviewResultRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> config.ExportPreviewResultResponse: - r"""Export [Preview][google.cloud.config.v1.Preview] results. - - .. 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 config_v1 - - def sample_export_preview_result(): - # Create a client - client = config_v1.ConfigClient() - - # Initialize request argument(s) - request = config_v1.ExportPreviewResultRequest( - parent="parent_value", - ) - - # Make the request - response = client.export_preview_result(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.config_v1.types.ExportPreviewResultRequest, dict]): - The request object. A request to export preview results. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each 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.config_v1.types.ExportPreviewResultResponse: - A response to ExportPreviewResult call. Contains preview - results. - - """ - # 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, config.ExportPreviewResultRequest): - request = config.ExportPreviewResultRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.export_preview_result] - - # 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 list_terraform_versions(self, - request: Optional[Union[config.ListTerraformVersionsRequest, 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.ListTerraformVersionsPager: - r"""Lists - [TerraformVersion][google.cloud.config.v1.TerraformVersion]s 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 config_v1 - - def sample_list_terraform_versions(): - # Create a client - client = config_v1.ConfigClient() - - # Initialize request argument(s) - request = config_v1.ListTerraformVersionsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_terraform_versions(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.config_v1.types.ListTerraformVersionsRequest, dict]): - The request object. The request message for the - ListTerraformVersions method. - parent (str): - Required. The parent in whose context the - TerraformVersions are listed. The parent value is in the - format: 'projects/{project_id}/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.config_v1.services.config.pagers.ListTerraformVersionsPager: - The response message for the ListTerraformVersions - 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, config.ListTerraformVersionsRequest): - request = config.ListTerraformVersionsRequest(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_terraform_versions] - - # 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.ListTerraformVersionsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_terraform_version(self, - request: Optional[Union[config.GetTerraformVersionRequest, 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]]] = (), - ) -> config.TerraformVersion: - r"""Gets details about a - [TerraformVersion][google.cloud.config.v1.TerraformVersion]. - - .. 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 config_v1 - - def sample_get_terraform_version(): - # Create a client - client = config_v1.ConfigClient() - - # Initialize request argument(s) - request = config_v1.GetTerraformVersionRequest( - name="name_value", - ) - - # Make the request - response = client.get_terraform_version(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.config_v1.types.GetTerraformVersionRequest, dict]): - The request object. The request message for the - GetTerraformVersion method. - name (str): - Required. The name of the TerraformVersion. Format: - 'projects/{project_id}/locations/{location}/terraformVersions/{terraform_version}' - - 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.config_v1.types.TerraformVersion: - A TerraformVersion represents the - support state the corresponding - Terraform version. - - """ - # 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, config.GetTerraformVersionRequest): - request = config.GetTerraformVersionRequest(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_terraform_version] - - # 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_resource_changes(self, - request: Optional[Union[config.ListResourceChangesRequest, 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.ListResourceChangesPager: - r"""Lists ResourceChanges for a given preview. - - .. 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 config_v1 - - def sample_list_resource_changes(): - # Create a client - client = config_v1.ConfigClient() - - # Initialize request argument(s) - request = config_v1.ListResourceChangesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_resource_changes(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.config_v1.types.ListResourceChangesRequest, dict]): - The request object. The request message for the - ListResourceChanges method. - parent (str): - Required. The parent in whose context the - ResourceChanges are listed. The parent value is in the - format: - 'projects/{project_id}/locations/{location}/previews/{preview}'. - - 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.config_v1.services.config.pagers.ListResourceChangesPager: - A response to a 'ListResourceChanges' - call. Contains a list of - ResourceChanges. - - 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, config.ListResourceChangesRequest): - request = config.ListResourceChangesRequest(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_changes] - - # 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.ListResourceChangesPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_resource_change(self, - request: Optional[Union[config.GetResourceChangeRequest, 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]]] = (), - ) -> config.ResourceChange: - r"""Get a ResourceChange for a given preview. - - .. 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 config_v1 - - def sample_get_resource_change(): - # Create a client - client = config_v1.ConfigClient() - - # Initialize request argument(s) - request = config_v1.GetResourceChangeRequest( - name="name_value", - ) - - # Make the request - response = client.get_resource_change(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.config_v1.types.GetResourceChangeRequest, dict]): - The request object. The request message for the - GetResourceChange method. - name (str): - Required. The name of the resource change to retrieve. - Format: - 'projects/{project_id}/locations/{location}/previews/{preview}/resourceChanges/{resource_change}'. - - 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.config_v1.types.ResourceChange: - A resource change represents a change - to a resource in the state file. - - """ - # 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, config.GetResourceChangeRequest): - request = config.GetResourceChangeRequest(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_resource_change] - - # 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_resource_drifts(self, - request: Optional[Union[config.ListResourceDriftsRequest, 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.ListResourceDriftsPager: - r"""List ResourceDrifts for a given preview. - - .. 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 config_v1 - - def sample_list_resource_drifts(): - # Create a client - client = config_v1.ConfigClient() - - # Initialize request argument(s) - request = config_v1.ListResourceDriftsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_resource_drifts(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.config_v1.types.ListResourceDriftsRequest, dict]): - The request object. The request message for the - ListResourceDrifts method. - parent (str): - Required. The parent in whose context the ResourceDrifts - are listed. The parent value is in the format: - 'projects/{project_id}/locations/{location}/previews/{preview}'. - - 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.config_v1.services.config.pagers.ListResourceDriftsPager: - A response to a 'ListResourceDrifts' - call. Contains a list of ResourceDrifts. - 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, config.ListResourceDriftsRequest): - request = config.ListResourceDriftsRequest(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_drifts] - - # 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.ListResourceDriftsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_resource_drift(self, - request: Optional[Union[config.GetResourceDriftRequest, 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]]] = (), - ) -> config.ResourceDrift: - r"""Get a ResourceDrift for a given preview. - - .. 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 config_v1 - - def sample_get_resource_drift(): - # Create a client - client = config_v1.ConfigClient() - - # Initialize request argument(s) - request = config_v1.GetResourceDriftRequest( - name="name_value", - ) - - # Make the request - response = client.get_resource_drift(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.config_v1.types.GetResourceDriftRequest, dict]): - The request object. The request message for the - GetResourceDrift method. - name (str): - Required. The name of the resource drift to retrieve. - Format: - 'projects/{project_id}/locations/{location}/previews/{preview}/resourceDrifts/{resource_drift}'. - - 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.config_v1.types.ResourceDrift: - A resource drift represents a drift - to a resource in the state file. - - """ - # 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, config.GetResourceDriftRequest): - request = config.GetResourceDriftRequest(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_resource_drift] - - # 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) -> "ConfigClient": - 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[operations_pb2.ListOperationsRequest] = 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 isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**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.name),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - try: - # Send the request. - response = rpc( - request, 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[operations_pb2.GetOperationRequest] = 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 isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**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.name),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - try: - # Send the request. - response = rpc( - request, 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[operations_pb2.DeleteOperationRequest] = 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 isinstance(request, dict): - request = operations_pb2.DeleteOperationRequest(**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.name),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - def cancel_operation( - self, - request: Optional[operations_pb2.CancelOperationRequest] = 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 isinstance(request, dict): - request = operations_pb2.CancelOperationRequest(**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.name),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - def set_iam_policy( - self, - request: Optional[iam_policy_pb2.SetIamPolicyRequest] = 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 isinstance(request, dict): - request = iam_policy_pb2.SetIamPolicyRequest(**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.resource),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - try: - # Send the request. - response = rpc( - request, 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[iam_policy_pb2.GetIamPolicyRequest] = 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 isinstance(request, dict): - request = iam_policy_pb2.GetIamPolicyRequest(**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.resource),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - try: - # Send the request. - response = rpc( - request, 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[iam_policy_pb2.TestIamPermissionsRequest] = 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 isinstance(request, dict): - request = iam_policy_pb2.TestIamPermissionsRequest(**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.resource),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - try: - # Send the request. - response = rpc( - request, 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[locations_pb2.GetLocationRequest] = 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 isinstance(request, dict): - request = locations_pb2.GetLocationRequest(**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.name),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - try: - # Send the request. - response = rpc( - request, 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[locations_pb2.ListLocationsRequest] = 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 isinstance(request, dict): - request = locations_pb2.ListLocationsRequest(**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.name),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - try: - # Send the request. - response = rpc( - request, 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__) - -if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER - DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ - -__all__ = ( - "ConfigClient", -) diff --git a/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/pagers.py b/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/pagers.py deleted file mode 100644 index b455a6d6256c..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/pagers.py +++ /dev/null @@ -1,1000 +0,0 @@ -# -*- 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. -# -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 -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator, Union -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.config_v1.types import config - - -class ListDeploymentsPager: - """A pager for iterating through ``list_deployments`` requests. - - This class thinly wraps an initial - :class:`google.cloud.config_v1.types.ListDeploymentsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``deployments`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListDeployments`` requests and continue to iterate - through the ``deployments`` field on the - corresponding responses. - - All the usual :class:`google.cloud.config_v1.types.ListDeploymentsResponse` - 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[..., config.ListDeploymentsResponse], - request: config.ListDeploymentsRequest, - response: config.ListDeploymentsResponse, - *, - 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.config_v1.types.ListDeploymentsRequest): - The initial request object. - response (google.cloud.config_v1.types.ListDeploymentsResponse): - 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 = config.ListDeploymentsRequest(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[config.ListDeploymentsResponse]: - 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[config.Deployment]: - for page in self.pages: - yield from page.deployments - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListDeploymentsAsyncPager: - """A pager for iterating through ``list_deployments`` requests. - - This class thinly wraps an initial - :class:`google.cloud.config_v1.types.ListDeploymentsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``deployments`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListDeployments`` requests and continue to iterate - through the ``deployments`` field on the - corresponding responses. - - All the usual :class:`google.cloud.config_v1.types.ListDeploymentsResponse` - 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[config.ListDeploymentsResponse]], - request: config.ListDeploymentsRequest, - response: config.ListDeploymentsResponse, - *, - 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.config_v1.types.ListDeploymentsRequest): - The initial request object. - response (google.cloud.config_v1.types.ListDeploymentsResponse): - 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 = config.ListDeploymentsRequest(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[config.ListDeploymentsResponse]: - 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[config.Deployment]: - async def async_generator(): - async for page in self.pages: - for response in page.deployments: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListRevisionsPager: - """A pager for iterating through ``list_revisions`` requests. - - This class thinly wraps an initial - :class:`google.cloud.config_v1.types.ListRevisionsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``revisions`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListRevisions`` requests and continue to iterate - through the ``revisions`` field on the - corresponding responses. - - All the usual :class:`google.cloud.config_v1.types.ListRevisionsResponse` - 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[..., config.ListRevisionsResponse], - request: config.ListRevisionsRequest, - response: config.ListRevisionsResponse, - *, - 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.config_v1.types.ListRevisionsRequest): - The initial request object. - response (google.cloud.config_v1.types.ListRevisionsResponse): - 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 = config.ListRevisionsRequest(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[config.ListRevisionsResponse]: - 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[config.Revision]: - for page in self.pages: - yield from page.revisions - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListRevisionsAsyncPager: - """A pager for iterating through ``list_revisions`` requests. - - This class thinly wraps an initial - :class:`google.cloud.config_v1.types.ListRevisionsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``revisions`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListRevisions`` requests and continue to iterate - through the ``revisions`` field on the - corresponding responses. - - All the usual :class:`google.cloud.config_v1.types.ListRevisionsResponse` - 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[config.ListRevisionsResponse]], - request: config.ListRevisionsRequest, - response: config.ListRevisionsResponse, - *, - 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.config_v1.types.ListRevisionsRequest): - The initial request object. - response (google.cloud.config_v1.types.ListRevisionsResponse): - 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 = config.ListRevisionsRequest(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[config.ListRevisionsResponse]: - 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[config.Revision]: - async def async_generator(): - async for page in self.pages: - for response in page.revisions: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListResourcesPager: - """A pager for iterating through ``list_resources`` requests. - - This class thinly wraps an initial - :class:`google.cloud.config_v1.types.ListResourcesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``resources`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListResources`` requests and continue to iterate - through the ``resources`` field on the - corresponding responses. - - All the usual :class:`google.cloud.config_v1.types.ListResourcesResponse` - 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[..., config.ListResourcesResponse], - request: config.ListResourcesRequest, - response: config.ListResourcesResponse, - *, - 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.config_v1.types.ListResourcesRequest): - The initial request object. - response (google.cloud.config_v1.types.ListResourcesResponse): - 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 = config.ListResourcesRequest(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[config.ListResourcesResponse]: - 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[config.Resource]: - for page in self.pages: - yield from page.resources - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListResourcesAsyncPager: - """A pager for iterating through ``list_resources`` requests. - - This class thinly wraps an initial - :class:`google.cloud.config_v1.types.ListResourcesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``resources`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListResources`` requests and continue to iterate - through the ``resources`` field on the - corresponding responses. - - All the usual :class:`google.cloud.config_v1.types.ListResourcesResponse` - 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[config.ListResourcesResponse]], - request: config.ListResourcesRequest, - response: config.ListResourcesResponse, - *, - 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.config_v1.types.ListResourcesRequest): - The initial request object. - response (google.cloud.config_v1.types.ListResourcesResponse): - 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 = config.ListResourcesRequest(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[config.ListResourcesResponse]: - 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[config.Resource]: - async def async_generator(): - async for page in self.pages: - for response in page.resources: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListPreviewsPager: - """A pager for iterating through ``list_previews`` requests. - - This class thinly wraps an initial - :class:`google.cloud.config_v1.types.ListPreviewsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``previews`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListPreviews`` requests and continue to iterate - through the ``previews`` field on the - corresponding responses. - - All the usual :class:`google.cloud.config_v1.types.ListPreviewsResponse` - 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[..., config.ListPreviewsResponse], - request: config.ListPreviewsRequest, - response: config.ListPreviewsResponse, - *, - 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.config_v1.types.ListPreviewsRequest): - The initial request object. - response (google.cloud.config_v1.types.ListPreviewsResponse): - 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 = config.ListPreviewsRequest(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[config.ListPreviewsResponse]: - 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[config.Preview]: - for page in self.pages: - yield from page.previews - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListPreviewsAsyncPager: - """A pager for iterating through ``list_previews`` requests. - - This class thinly wraps an initial - :class:`google.cloud.config_v1.types.ListPreviewsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``previews`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListPreviews`` requests and continue to iterate - through the ``previews`` field on the - corresponding responses. - - All the usual :class:`google.cloud.config_v1.types.ListPreviewsResponse` - 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[config.ListPreviewsResponse]], - request: config.ListPreviewsRequest, - response: config.ListPreviewsResponse, - *, - 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.config_v1.types.ListPreviewsRequest): - The initial request object. - response (google.cloud.config_v1.types.ListPreviewsResponse): - 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 = config.ListPreviewsRequest(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[config.ListPreviewsResponse]: - 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[config.Preview]: - async def async_generator(): - async for page in self.pages: - for response in page.previews: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListTerraformVersionsPager: - """A pager for iterating through ``list_terraform_versions`` requests. - - This class thinly wraps an initial - :class:`google.cloud.config_v1.types.ListTerraformVersionsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``terraform_versions`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListTerraformVersions`` requests and continue to iterate - through the ``terraform_versions`` field on the - corresponding responses. - - All the usual :class:`google.cloud.config_v1.types.ListTerraformVersionsResponse` - 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[..., config.ListTerraformVersionsResponse], - request: config.ListTerraformVersionsRequest, - response: config.ListTerraformVersionsResponse, - *, - 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.config_v1.types.ListTerraformVersionsRequest): - The initial request object. - response (google.cloud.config_v1.types.ListTerraformVersionsResponse): - 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 = config.ListTerraformVersionsRequest(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[config.ListTerraformVersionsResponse]: - 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[config.TerraformVersion]: - for page in self.pages: - yield from page.terraform_versions - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListTerraformVersionsAsyncPager: - """A pager for iterating through ``list_terraform_versions`` requests. - - This class thinly wraps an initial - :class:`google.cloud.config_v1.types.ListTerraformVersionsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``terraform_versions`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListTerraformVersions`` requests and continue to iterate - through the ``terraform_versions`` field on the - corresponding responses. - - All the usual :class:`google.cloud.config_v1.types.ListTerraformVersionsResponse` - 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[config.ListTerraformVersionsResponse]], - request: config.ListTerraformVersionsRequest, - response: config.ListTerraformVersionsResponse, - *, - 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.config_v1.types.ListTerraformVersionsRequest): - The initial request object. - response (google.cloud.config_v1.types.ListTerraformVersionsResponse): - 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 = config.ListTerraformVersionsRequest(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[config.ListTerraformVersionsResponse]: - 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[config.TerraformVersion]: - async def async_generator(): - async for page in self.pages: - for response in page.terraform_versions: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListResourceChangesPager: - """A pager for iterating through ``list_resource_changes`` requests. - - This class thinly wraps an initial - :class:`google.cloud.config_v1.types.ListResourceChangesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``resource_changes`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListResourceChanges`` requests and continue to iterate - through the ``resource_changes`` field on the - corresponding responses. - - All the usual :class:`google.cloud.config_v1.types.ListResourceChangesResponse` - 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[..., config.ListResourceChangesResponse], - request: config.ListResourceChangesRequest, - response: config.ListResourceChangesResponse, - *, - 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.config_v1.types.ListResourceChangesRequest): - The initial request object. - response (google.cloud.config_v1.types.ListResourceChangesResponse): - 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 = config.ListResourceChangesRequest(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[config.ListResourceChangesResponse]: - 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[config.ResourceChange]: - for page in self.pages: - yield from page.resource_changes - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListResourceChangesAsyncPager: - """A pager for iterating through ``list_resource_changes`` requests. - - This class thinly wraps an initial - :class:`google.cloud.config_v1.types.ListResourceChangesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``resource_changes`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListResourceChanges`` requests and continue to iterate - through the ``resource_changes`` field on the - corresponding responses. - - All the usual :class:`google.cloud.config_v1.types.ListResourceChangesResponse` - 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[config.ListResourceChangesResponse]], - request: config.ListResourceChangesRequest, - response: config.ListResourceChangesResponse, - *, - 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.config_v1.types.ListResourceChangesRequest): - The initial request object. - response (google.cloud.config_v1.types.ListResourceChangesResponse): - 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 = config.ListResourceChangesRequest(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[config.ListResourceChangesResponse]: - 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[config.ResourceChange]: - async def async_generator(): - async for page in self.pages: - for response in page.resource_changes: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListResourceDriftsPager: - """A pager for iterating through ``list_resource_drifts`` requests. - - This class thinly wraps an initial - :class:`google.cloud.config_v1.types.ListResourceDriftsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``resource_drifts`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListResourceDrifts`` requests and continue to iterate - through the ``resource_drifts`` field on the - corresponding responses. - - All the usual :class:`google.cloud.config_v1.types.ListResourceDriftsResponse` - 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[..., config.ListResourceDriftsResponse], - request: config.ListResourceDriftsRequest, - response: config.ListResourceDriftsResponse, - *, - 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.config_v1.types.ListResourceDriftsRequest): - The initial request object. - response (google.cloud.config_v1.types.ListResourceDriftsResponse): - 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 = config.ListResourceDriftsRequest(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[config.ListResourceDriftsResponse]: - 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[config.ResourceDrift]: - for page in self.pages: - yield from page.resource_drifts - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListResourceDriftsAsyncPager: - """A pager for iterating through ``list_resource_drifts`` requests. - - This class thinly wraps an initial - :class:`google.cloud.config_v1.types.ListResourceDriftsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``resource_drifts`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListResourceDrifts`` requests and continue to iterate - through the ``resource_drifts`` field on the - corresponding responses. - - All the usual :class:`google.cloud.config_v1.types.ListResourceDriftsResponse` - 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[config.ListResourceDriftsResponse]], - request: config.ListResourceDriftsRequest, - response: config.ListResourceDriftsResponse, - *, - 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.config_v1.types.ListResourceDriftsRequest): - The initial request object. - response (google.cloud.config_v1.types.ListResourceDriftsResponse): - 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 = config.ListResourceDriftsRequest(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[config.ListResourceDriftsResponse]: - 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[config.ResourceDrift]: - async def async_generator(): - async for page in self.pages: - for response in page.resource_drifts: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/transports/README.rst b/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/transports/README.rst deleted file mode 100644 index 78e592f08a90..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/transports/README.rst +++ /dev/null @@ -1,9 +0,0 @@ - -transport inheritance structure -_______________________________ - -`ConfigTransport` is the ABC for all transports. -- public child `ConfigGrpcTransport` for sync gRPC transport (defined in `grpc.py`). -- public child `ConfigGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). -- private child `_BaseConfigRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). -- public child `ConfigRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/transports/__init__.py b/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/transports/__init__.py deleted file mode 100644 index dae31983d4d2..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- 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. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import ConfigTransport -from .grpc import ConfigGrpcTransport -from .grpc_asyncio import ConfigGrpcAsyncIOTransport -from .rest import ConfigRestTransport -from .rest import ConfigRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[ConfigTransport]] -_transport_registry['grpc'] = ConfigGrpcTransport -_transport_registry['grpc_asyncio'] = ConfigGrpcAsyncIOTransport -_transport_registry['rest'] = ConfigRestTransport - -__all__ = ( - 'ConfigTransport', - 'ConfigGrpcTransport', - 'ConfigGrpcAsyncIOTransport', - 'ConfigRestTransport', - 'ConfigRestInterceptor', -) diff --git a/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/transports/base.py b/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/transports/base.py deleted file mode 100644 index 6bd22c3c5db9..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/transports/base.py +++ /dev/null @@ -1,661 +0,0 @@ -# -*- 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. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union - -from google.cloud.config_v1 import gapic_version as package_version - -import google.auth # type: ignore -import google.api_core -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.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore -import google.protobuf - -from google.cloud.config_v1.types import config -from google.cloud.location import locations_pb2 # type: ignore -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - -if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER - DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ - - -class ConfigTransport(abc.ABC): - """Abstract transport class for Config.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'config.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: 'config.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]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - 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. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # 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_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None and not self._ignore_credentials: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # 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 - - @property - def host(self): - return self._host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.list_deployments: gapic_v1.method.wrap_method( - self.list_deployments, - default_timeout=None, - client_info=client_info, - ), - self.get_deployment: gapic_v1.method.wrap_method( - self.get_deployment, - default_timeout=None, - client_info=client_info, - ), - self.create_deployment: gapic_v1.method.wrap_method( - self.create_deployment, - default_timeout=None, - client_info=client_info, - ), - self.update_deployment: gapic_v1.method.wrap_method( - self.update_deployment, - default_timeout=None, - client_info=client_info, - ), - self.delete_deployment: gapic_v1.method.wrap_method( - self.delete_deployment, - default_timeout=None, - client_info=client_info, - ), - self.list_revisions: gapic_v1.method.wrap_method( - self.list_revisions, - default_timeout=None, - client_info=client_info, - ), - self.get_revision: gapic_v1.method.wrap_method( - self.get_revision, - default_timeout=None, - client_info=client_info, - ), - self.get_resource: gapic_v1.method.wrap_method( - self.get_resource, - default_timeout=None, - client_info=client_info, - ), - self.list_resources: gapic_v1.method.wrap_method( - self.list_resources, - default_timeout=None, - client_info=client_info, - ), - self.export_deployment_statefile: gapic_v1.method.wrap_method( - self.export_deployment_statefile, - default_timeout=None, - client_info=client_info, - ), - self.export_revision_statefile: gapic_v1.method.wrap_method( - self.export_revision_statefile, - default_timeout=None, - client_info=client_info, - ), - self.import_statefile: gapic_v1.method.wrap_method( - self.import_statefile, - default_timeout=None, - client_info=client_info, - ), - self.delete_statefile: gapic_v1.method.wrap_method( - self.delete_statefile, - default_timeout=None, - client_info=client_info, - ), - self.lock_deployment: gapic_v1.method.wrap_method( - self.lock_deployment, - default_timeout=None, - client_info=client_info, - ), - self.unlock_deployment: gapic_v1.method.wrap_method( - self.unlock_deployment, - default_timeout=None, - client_info=client_info, - ), - self.export_lock_info: gapic_v1.method.wrap_method( - self.export_lock_info, - default_timeout=None, - client_info=client_info, - ), - self.create_preview: gapic_v1.method.wrap_method( - self.create_preview, - default_timeout=None, - client_info=client_info, - ), - self.get_preview: gapic_v1.method.wrap_method( - self.get_preview, - default_timeout=None, - client_info=client_info, - ), - self.list_previews: gapic_v1.method.wrap_method( - self.list_previews, - default_timeout=None, - client_info=client_info, - ), - self.delete_preview: gapic_v1.method.wrap_method( - self.delete_preview, - default_timeout=None, - client_info=client_info, - ), - self.export_preview_result: gapic_v1.method.wrap_method( - self.export_preview_result, - default_timeout=None, - client_info=client_info, - ), - self.list_terraform_versions: gapic_v1.method.wrap_method( - self.list_terraform_versions, - default_timeout=None, - client_info=client_info, - ), - self.get_terraform_version: gapic_v1.method.wrap_method( - self.get_terraform_version, - default_timeout=None, - client_info=client_info, - ), - self.list_resource_changes: gapic_v1.method.wrap_method( - self.list_resource_changes, - default_timeout=None, - client_info=client_info, - ), - self.get_resource_change: gapic_v1.method.wrap_method( - self.get_resource_change, - default_timeout=None, - client_info=client_info, - ), - self.list_resource_drifts: gapic_v1.method.wrap_method( - self.list_resource_drifts, - default_timeout=None, - client_info=client_info, - ), - self.get_resource_drift: gapic_v1.method.wrap_method( - self.get_resource_drift, - 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_deployments(self) -> Callable[ - [config.ListDeploymentsRequest], - Union[ - config.ListDeploymentsResponse, - Awaitable[config.ListDeploymentsResponse] - ]]: - raise NotImplementedError() - - @property - def get_deployment(self) -> Callable[ - [config.GetDeploymentRequest], - Union[ - config.Deployment, - Awaitable[config.Deployment] - ]]: - raise NotImplementedError() - - @property - def create_deployment(self) -> Callable[ - [config.CreateDeploymentRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def update_deployment(self) -> Callable[ - [config.UpdateDeploymentRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def delete_deployment(self) -> Callable[ - [config.DeleteDeploymentRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def list_revisions(self) -> Callable[ - [config.ListRevisionsRequest], - Union[ - config.ListRevisionsResponse, - Awaitable[config.ListRevisionsResponse] - ]]: - raise NotImplementedError() - - @property - def get_revision(self) -> Callable[ - [config.GetRevisionRequest], - Union[ - config.Revision, - Awaitable[config.Revision] - ]]: - raise NotImplementedError() - - @property - def get_resource(self) -> Callable[ - [config.GetResourceRequest], - Union[ - config.Resource, - Awaitable[config.Resource] - ]]: - raise NotImplementedError() - - @property - def list_resources(self) -> Callable[ - [config.ListResourcesRequest], - Union[ - config.ListResourcesResponse, - Awaitable[config.ListResourcesResponse] - ]]: - raise NotImplementedError() - - @property - def export_deployment_statefile(self) -> Callable[ - [config.ExportDeploymentStatefileRequest], - Union[ - config.Statefile, - Awaitable[config.Statefile] - ]]: - raise NotImplementedError() - - @property - def export_revision_statefile(self) -> Callable[ - [config.ExportRevisionStatefileRequest], - Union[ - config.Statefile, - Awaitable[config.Statefile] - ]]: - raise NotImplementedError() - - @property - def import_statefile(self) -> Callable[ - [config.ImportStatefileRequest], - Union[ - config.Statefile, - Awaitable[config.Statefile] - ]]: - raise NotImplementedError() - - @property - def delete_statefile(self) -> Callable[ - [config.DeleteStatefileRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def lock_deployment(self) -> Callable[ - [config.LockDeploymentRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def unlock_deployment(self) -> Callable[ - [config.UnlockDeploymentRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def export_lock_info(self) -> Callable[ - [config.ExportLockInfoRequest], - Union[ - config.LockInfo, - Awaitable[config.LockInfo] - ]]: - raise NotImplementedError() - - @property - def create_preview(self) -> Callable[ - [config.CreatePreviewRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def get_preview(self) -> Callable[ - [config.GetPreviewRequest], - Union[ - config.Preview, - Awaitable[config.Preview] - ]]: - raise NotImplementedError() - - @property - def list_previews(self) -> Callable[ - [config.ListPreviewsRequest], - Union[ - config.ListPreviewsResponse, - Awaitable[config.ListPreviewsResponse] - ]]: - raise NotImplementedError() - - @property - def delete_preview(self) -> Callable[ - [config.DeletePreviewRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def export_preview_result(self) -> Callable[ - [config.ExportPreviewResultRequest], - Union[ - config.ExportPreviewResultResponse, - Awaitable[config.ExportPreviewResultResponse] - ]]: - raise NotImplementedError() - - @property - def list_terraform_versions(self) -> Callable[ - [config.ListTerraformVersionsRequest], - Union[ - config.ListTerraformVersionsResponse, - Awaitable[config.ListTerraformVersionsResponse] - ]]: - raise NotImplementedError() - - @property - def get_terraform_version(self) -> Callable[ - [config.GetTerraformVersionRequest], - Union[ - config.TerraformVersion, - Awaitable[config.TerraformVersion] - ]]: - raise NotImplementedError() - - @property - def list_resource_changes(self) -> Callable[ - [config.ListResourceChangesRequest], - Union[ - config.ListResourceChangesResponse, - Awaitable[config.ListResourceChangesResponse] - ]]: - raise NotImplementedError() - - @property - def get_resource_change(self) -> Callable[ - [config.GetResourceChangeRequest], - Union[ - config.ResourceChange, - Awaitable[config.ResourceChange] - ]]: - raise NotImplementedError() - - @property - def list_resource_drifts(self) -> Callable[ - [config.ListResourceDriftsRequest], - Union[ - config.ListResourceDriftsResponse, - Awaitable[config.ListResourceDriftsResponse] - ]]: - raise NotImplementedError() - - @property - def get_resource_drift(self) -> Callable[ - [config.GetResourceDriftRequest], - Union[ - config.ResourceDrift, - Awaitable[config.ResourceDrift] - ]]: - 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__ = ( - 'ConfigTransport', -) diff --git a/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/transports/grpc.py b/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/transports/grpc.py deleted file mode 100644 index b8ed39d20f21..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/transports/grpc.py +++ /dev/null @@ -1,1246 +0,0 @@ -# -*- 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. -# -import json -import logging as std_logging -import pickle -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import operations_v1 -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.protobuf.json_format import MessageToJson -import google.protobuf.message - -import grpc # type: ignore -import proto # type: ignore - -from google.cloud.config_v1.types import config -from google.cloud.location import locations_pb2 # type: ignore -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from .base import ConfigTransport, DEFAULT_CLIENT_INFO - -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)}" - - 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.config.v1.Config", - "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)}" - grpc_response = { - "payload": response_payload, - "metadata": metadata, - "status": "OK", - } - _LOGGER.debug( - f"Received response for {client_call_details.method}.", - extra = { - "serviceName": "google.cloud.config.v1.Config", - "rpcName": client_call_details.method, - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class ConfigGrpcTransport(ConfigTransport): - """gRPC backend transport for Config. - - Infrastructure Manager is a managed service that automates - the deployment and management of Google Cloud infrastructure - 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 = 'config.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: 'config.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]): 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. - 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. - - 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 = 'config.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]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - 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_deployments(self) -> Callable[ - [config.ListDeploymentsRequest], - config.ListDeploymentsResponse]: - r"""Return a callable for the list deployments method over gRPC. - - Lists [Deployment][google.cloud.config.v1.Deployment]s in a - given project and location. - - Returns: - Callable[[~.ListDeploymentsRequest], - ~.ListDeploymentsResponse]: - 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_deployments' not in self._stubs: - self._stubs['list_deployments'] = self._logged_channel.unary_unary( - '/google.cloud.config.v1.Config/ListDeployments', - request_serializer=config.ListDeploymentsRequest.serialize, - response_deserializer=config.ListDeploymentsResponse.deserialize, - ) - return self._stubs['list_deployments'] - - @property - def get_deployment(self) -> Callable[ - [config.GetDeploymentRequest], - config.Deployment]: - r"""Return a callable for the get deployment method over gRPC. - - Gets details about a - [Deployment][google.cloud.config.v1.Deployment]. - - Returns: - Callable[[~.GetDeploymentRequest], - ~.Deployment]: - 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_deployment' not in self._stubs: - self._stubs['get_deployment'] = self._logged_channel.unary_unary( - '/google.cloud.config.v1.Config/GetDeployment', - request_serializer=config.GetDeploymentRequest.serialize, - response_deserializer=config.Deployment.deserialize, - ) - return self._stubs['get_deployment'] - - @property - def create_deployment(self) -> Callable[ - [config.CreateDeploymentRequest], - operations_pb2.Operation]: - r"""Return a callable for the create deployment method over gRPC. - - Creates a [Deployment][google.cloud.config.v1.Deployment]. - - Returns: - Callable[[~.CreateDeploymentRequest], - ~.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_deployment' not in self._stubs: - self._stubs['create_deployment'] = self._logged_channel.unary_unary( - '/google.cloud.config.v1.Config/CreateDeployment', - request_serializer=config.CreateDeploymentRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_deployment'] - - @property - def update_deployment(self) -> Callable[ - [config.UpdateDeploymentRequest], - operations_pb2.Operation]: - r"""Return a callable for the update deployment method over gRPC. - - Updates a [Deployment][google.cloud.config.v1.Deployment]. - - Returns: - Callable[[~.UpdateDeploymentRequest], - ~.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_deployment' not in self._stubs: - self._stubs['update_deployment'] = self._logged_channel.unary_unary( - '/google.cloud.config.v1.Config/UpdateDeployment', - request_serializer=config.UpdateDeploymentRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_deployment'] - - @property - def delete_deployment(self) -> Callable[ - [config.DeleteDeploymentRequest], - operations_pb2.Operation]: - r"""Return a callable for the delete deployment method over gRPC. - - Deletes a [Deployment][google.cloud.config.v1.Deployment]. - - Returns: - Callable[[~.DeleteDeploymentRequest], - ~.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_deployment' not in self._stubs: - self._stubs['delete_deployment'] = self._logged_channel.unary_unary( - '/google.cloud.config.v1.Config/DeleteDeployment', - request_serializer=config.DeleteDeploymentRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_deployment'] - - @property - def list_revisions(self) -> Callable[ - [config.ListRevisionsRequest], - config.ListRevisionsResponse]: - r"""Return a callable for the list revisions method over gRPC. - - Lists [Revision][google.cloud.config.v1.Revision]s of a - deployment. - - Returns: - Callable[[~.ListRevisionsRequest], - ~.ListRevisionsResponse]: - 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_revisions' not in self._stubs: - self._stubs['list_revisions'] = self._logged_channel.unary_unary( - '/google.cloud.config.v1.Config/ListRevisions', - request_serializer=config.ListRevisionsRequest.serialize, - response_deserializer=config.ListRevisionsResponse.deserialize, - ) - return self._stubs['list_revisions'] - - @property - def get_revision(self) -> Callable[ - [config.GetRevisionRequest], - config.Revision]: - r"""Return a callable for the get revision method over gRPC. - - Gets details about a - [Revision][google.cloud.config.v1.Revision]. - - Returns: - Callable[[~.GetRevisionRequest], - ~.Revision]: - 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_revision' not in self._stubs: - self._stubs['get_revision'] = self._logged_channel.unary_unary( - '/google.cloud.config.v1.Config/GetRevision', - request_serializer=config.GetRevisionRequest.serialize, - response_deserializer=config.Revision.deserialize, - ) - return self._stubs['get_revision'] - - @property - def get_resource(self) -> Callable[ - [config.GetResourceRequest], - config.Resource]: - r"""Return a callable for the get resource method over gRPC. - - Gets details about a [Resource][google.cloud.config.v1.Resource] - deployed by Infra Manager. - - Returns: - Callable[[~.GetResourceRequest], - ~.Resource]: - 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_resource' not in self._stubs: - self._stubs['get_resource'] = self._logged_channel.unary_unary( - '/google.cloud.config.v1.Config/GetResource', - request_serializer=config.GetResourceRequest.serialize, - response_deserializer=config.Resource.deserialize, - ) - return self._stubs['get_resource'] - - @property - def list_resources(self) -> Callable[ - [config.ListResourcesRequest], - config.ListResourcesResponse]: - r"""Return a callable for the list resources method over gRPC. - - Lists [Resources][google.cloud.config.v1.Resource] in a given - revision. - - Returns: - Callable[[~.ListResourcesRequest], - ~.ListResourcesResponse]: - 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_resources' not in self._stubs: - self._stubs['list_resources'] = self._logged_channel.unary_unary( - '/google.cloud.config.v1.Config/ListResources', - request_serializer=config.ListResourcesRequest.serialize, - response_deserializer=config.ListResourcesResponse.deserialize, - ) - return self._stubs['list_resources'] - - @property - def export_deployment_statefile(self) -> Callable[ - [config.ExportDeploymentStatefileRequest], - config.Statefile]: - r"""Return a callable for the export deployment statefile method over gRPC. - - Exports Terraform state file from a given deployment. - - Returns: - Callable[[~.ExportDeploymentStatefileRequest], - ~.Statefile]: - 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 'export_deployment_statefile' not in self._stubs: - self._stubs['export_deployment_statefile'] = self._logged_channel.unary_unary( - '/google.cloud.config.v1.Config/ExportDeploymentStatefile', - request_serializer=config.ExportDeploymentStatefileRequest.serialize, - response_deserializer=config.Statefile.deserialize, - ) - return self._stubs['export_deployment_statefile'] - - @property - def export_revision_statefile(self) -> Callable[ - [config.ExportRevisionStatefileRequest], - config.Statefile]: - r"""Return a callable for the export revision statefile method over gRPC. - - Exports Terraform state file from a given revision. - - Returns: - Callable[[~.ExportRevisionStatefileRequest], - ~.Statefile]: - 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 'export_revision_statefile' not in self._stubs: - self._stubs['export_revision_statefile'] = self._logged_channel.unary_unary( - '/google.cloud.config.v1.Config/ExportRevisionStatefile', - request_serializer=config.ExportRevisionStatefileRequest.serialize, - response_deserializer=config.Statefile.deserialize, - ) - return self._stubs['export_revision_statefile'] - - @property - def import_statefile(self) -> Callable[ - [config.ImportStatefileRequest], - config.Statefile]: - r"""Return a callable for the import statefile method over gRPC. - - Imports Terraform state file in a given deployment. - The state file does not take effect until the Deployment - has been unlocked. - - Returns: - Callable[[~.ImportStatefileRequest], - ~.Statefile]: - 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 'import_statefile' not in self._stubs: - self._stubs['import_statefile'] = self._logged_channel.unary_unary( - '/google.cloud.config.v1.Config/ImportStatefile', - request_serializer=config.ImportStatefileRequest.serialize, - response_deserializer=config.Statefile.deserialize, - ) - return self._stubs['import_statefile'] - - @property - def delete_statefile(self) -> Callable[ - [config.DeleteStatefileRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete statefile method over gRPC. - - Deletes Terraform state file in a given deployment. - - Returns: - Callable[[~.DeleteStatefileRequest], - ~.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_statefile' not in self._stubs: - self._stubs['delete_statefile'] = self._logged_channel.unary_unary( - '/google.cloud.config.v1.Config/DeleteStatefile', - request_serializer=config.DeleteStatefileRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_statefile'] - - @property - def lock_deployment(self) -> Callable[ - [config.LockDeploymentRequest], - operations_pb2.Operation]: - r"""Return a callable for the lock deployment method over gRPC. - - Locks a deployment. - - Returns: - Callable[[~.LockDeploymentRequest], - ~.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 'lock_deployment' not in self._stubs: - self._stubs['lock_deployment'] = self._logged_channel.unary_unary( - '/google.cloud.config.v1.Config/LockDeployment', - request_serializer=config.LockDeploymentRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['lock_deployment'] - - @property - def unlock_deployment(self) -> Callable[ - [config.UnlockDeploymentRequest], - operations_pb2.Operation]: - r"""Return a callable for the unlock deployment method over gRPC. - - Unlocks a locked deployment. - - Returns: - Callable[[~.UnlockDeploymentRequest], - ~.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 'unlock_deployment' not in self._stubs: - self._stubs['unlock_deployment'] = self._logged_channel.unary_unary( - '/google.cloud.config.v1.Config/UnlockDeployment', - request_serializer=config.UnlockDeploymentRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['unlock_deployment'] - - @property - def export_lock_info(self) -> Callable[ - [config.ExportLockInfoRequest], - config.LockInfo]: - r"""Return a callable for the export lock info method over gRPC. - - Exports the lock info on a locked deployment. - - Returns: - Callable[[~.ExportLockInfoRequest], - ~.LockInfo]: - 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 'export_lock_info' not in self._stubs: - self._stubs['export_lock_info'] = self._logged_channel.unary_unary( - '/google.cloud.config.v1.Config/ExportLockInfo', - request_serializer=config.ExportLockInfoRequest.serialize, - response_deserializer=config.LockInfo.deserialize, - ) - return self._stubs['export_lock_info'] - - @property - def create_preview(self) -> Callable[ - [config.CreatePreviewRequest], - operations_pb2.Operation]: - r"""Return a callable for the create preview method over gRPC. - - Creates a [Preview][google.cloud.config.v1.Preview]. - - Returns: - Callable[[~.CreatePreviewRequest], - ~.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_preview' not in self._stubs: - self._stubs['create_preview'] = self._logged_channel.unary_unary( - '/google.cloud.config.v1.Config/CreatePreview', - request_serializer=config.CreatePreviewRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_preview'] - - @property - def get_preview(self) -> Callable[ - [config.GetPreviewRequest], - config.Preview]: - r"""Return a callable for the get preview method over gRPC. - - Gets details about a [Preview][google.cloud.config.v1.Preview]. - - Returns: - Callable[[~.GetPreviewRequest], - ~.Preview]: - 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_preview' not in self._stubs: - self._stubs['get_preview'] = self._logged_channel.unary_unary( - '/google.cloud.config.v1.Config/GetPreview', - request_serializer=config.GetPreviewRequest.serialize, - response_deserializer=config.Preview.deserialize, - ) - return self._stubs['get_preview'] - - @property - def list_previews(self) -> Callable[ - [config.ListPreviewsRequest], - config.ListPreviewsResponse]: - r"""Return a callable for the list previews method over gRPC. - - Lists [Preview][google.cloud.config.v1.Preview]s in a given - project and location. - - Returns: - Callable[[~.ListPreviewsRequest], - ~.ListPreviewsResponse]: - 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_previews' not in self._stubs: - self._stubs['list_previews'] = self._logged_channel.unary_unary( - '/google.cloud.config.v1.Config/ListPreviews', - request_serializer=config.ListPreviewsRequest.serialize, - response_deserializer=config.ListPreviewsResponse.deserialize, - ) - return self._stubs['list_previews'] - - @property - def delete_preview(self) -> Callable[ - [config.DeletePreviewRequest], - operations_pb2.Operation]: - r"""Return a callable for the delete preview method over gRPC. - - Deletes a [Preview][google.cloud.config.v1.Preview]. - - Returns: - Callable[[~.DeletePreviewRequest], - ~.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_preview' not in self._stubs: - self._stubs['delete_preview'] = self._logged_channel.unary_unary( - '/google.cloud.config.v1.Config/DeletePreview', - request_serializer=config.DeletePreviewRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_preview'] - - @property - def export_preview_result(self) -> Callable[ - [config.ExportPreviewResultRequest], - config.ExportPreviewResultResponse]: - r"""Return a callable for the export preview result method over gRPC. - - Export [Preview][google.cloud.config.v1.Preview] results. - - Returns: - Callable[[~.ExportPreviewResultRequest], - ~.ExportPreviewResultResponse]: - 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 'export_preview_result' not in self._stubs: - self._stubs['export_preview_result'] = self._logged_channel.unary_unary( - '/google.cloud.config.v1.Config/ExportPreviewResult', - request_serializer=config.ExportPreviewResultRequest.serialize, - response_deserializer=config.ExportPreviewResultResponse.deserialize, - ) - return self._stubs['export_preview_result'] - - @property - def list_terraform_versions(self) -> Callable[ - [config.ListTerraformVersionsRequest], - config.ListTerraformVersionsResponse]: - r"""Return a callable for the list terraform versions method over gRPC. - - Lists - [TerraformVersion][google.cloud.config.v1.TerraformVersion]s in - a given project and location. - - Returns: - Callable[[~.ListTerraformVersionsRequest], - ~.ListTerraformVersionsResponse]: - 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_terraform_versions' not in self._stubs: - self._stubs['list_terraform_versions'] = self._logged_channel.unary_unary( - '/google.cloud.config.v1.Config/ListTerraformVersions', - request_serializer=config.ListTerraformVersionsRequest.serialize, - response_deserializer=config.ListTerraformVersionsResponse.deserialize, - ) - return self._stubs['list_terraform_versions'] - - @property - def get_terraform_version(self) -> Callable[ - [config.GetTerraformVersionRequest], - config.TerraformVersion]: - r"""Return a callable for the get terraform version method over gRPC. - - Gets details about a - [TerraformVersion][google.cloud.config.v1.TerraformVersion]. - - Returns: - Callable[[~.GetTerraformVersionRequest], - ~.TerraformVersion]: - 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_terraform_version' not in self._stubs: - self._stubs['get_terraform_version'] = self._logged_channel.unary_unary( - '/google.cloud.config.v1.Config/GetTerraformVersion', - request_serializer=config.GetTerraformVersionRequest.serialize, - response_deserializer=config.TerraformVersion.deserialize, - ) - return self._stubs['get_terraform_version'] - - @property - def list_resource_changes(self) -> Callable[ - [config.ListResourceChangesRequest], - config.ListResourceChangesResponse]: - r"""Return a callable for the list resource changes method over gRPC. - - Lists ResourceChanges for a given preview. - - Returns: - Callable[[~.ListResourceChangesRequest], - ~.ListResourceChangesResponse]: - 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_changes' not in self._stubs: - self._stubs['list_resource_changes'] = self._logged_channel.unary_unary( - '/google.cloud.config.v1.Config/ListResourceChanges', - request_serializer=config.ListResourceChangesRequest.serialize, - response_deserializer=config.ListResourceChangesResponse.deserialize, - ) - return self._stubs['list_resource_changes'] - - @property - def get_resource_change(self) -> Callable[ - [config.GetResourceChangeRequest], - config.ResourceChange]: - r"""Return a callable for the get resource change method over gRPC. - - Get a ResourceChange for a given preview. - - Returns: - Callable[[~.GetResourceChangeRequest], - ~.ResourceChange]: - 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_resource_change' not in self._stubs: - self._stubs['get_resource_change'] = self._logged_channel.unary_unary( - '/google.cloud.config.v1.Config/GetResourceChange', - request_serializer=config.GetResourceChangeRequest.serialize, - response_deserializer=config.ResourceChange.deserialize, - ) - return self._stubs['get_resource_change'] - - @property - def list_resource_drifts(self) -> Callable[ - [config.ListResourceDriftsRequest], - config.ListResourceDriftsResponse]: - r"""Return a callable for the list resource drifts method over gRPC. - - List ResourceDrifts for a given preview. - - Returns: - Callable[[~.ListResourceDriftsRequest], - ~.ListResourceDriftsResponse]: - 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_drifts' not in self._stubs: - self._stubs['list_resource_drifts'] = self._logged_channel.unary_unary( - '/google.cloud.config.v1.Config/ListResourceDrifts', - request_serializer=config.ListResourceDriftsRequest.serialize, - response_deserializer=config.ListResourceDriftsResponse.deserialize, - ) - return self._stubs['list_resource_drifts'] - - @property - def get_resource_drift(self) -> Callable[ - [config.GetResourceDriftRequest], - config.ResourceDrift]: - r"""Return a callable for the get resource drift method over gRPC. - - Get a ResourceDrift for a given preview. - - Returns: - Callable[[~.GetResourceDriftRequest], - ~.ResourceDrift]: - 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_resource_drift' not in self._stubs: - self._stubs['get_resource_drift'] = self._logged_channel.unary_unary( - '/google.cloud.config.v1.Config/GetResourceDrift', - request_serializer=config.GetResourceDriftRequest.serialize, - response_deserializer=config.ResourceDrift.deserialize, - ) - return self._stubs['get_resource_drift'] - - 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__ = ( - 'ConfigGrpcTransport', -) diff --git a/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/transports/grpc_asyncio.py deleted file mode 100644 index 5b8714d9636d..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/transports/grpc_asyncio.py +++ /dev/null @@ -1,1442 +0,0 @@ -# -*- 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. -# -import inspect -import json -import pickle -import logging as std_logging -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.api_core import exceptions as core_exceptions -from google.api_core import retry_async as retries -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.protobuf.json_format import MessageToJson -import google.protobuf.message - -import grpc # type: ignore -import proto # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.config_v1.types import config -from google.cloud.location import locations_pb2 # type: ignore -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from .base import ConfigTransport, DEFAULT_CLIENT_INFO -from .grpc import ConfigGrpcTransport - -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)}" - - 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.config.v1.Config", - "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)}" - grpc_response = { - "payload": response_payload, - "metadata": metadata, - "status": "OK", - } - _LOGGER.debug( - f"Received response to rpc {client_call_details.method}.", - extra = { - "serviceName": "google.cloud.config.v1.Config", - "rpcName": str(client_call_details.method), - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class ConfigGrpcAsyncIOTransport(ConfigTransport): - """gRPC AsyncIO backend transport for Config. - - Infrastructure Manager is a managed service that automates - the deployment and management of Google Cloud infrastructure - 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 = 'config.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]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - 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 = 'config.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: 'config.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]): 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. - 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. - - 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_deployments(self) -> Callable[ - [config.ListDeploymentsRequest], - Awaitable[config.ListDeploymentsResponse]]: - r"""Return a callable for the list deployments method over gRPC. - - Lists [Deployment][google.cloud.config.v1.Deployment]s in a - given project and location. - - Returns: - Callable[[~.ListDeploymentsRequest], - Awaitable[~.ListDeploymentsResponse]]: - 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_deployments' not in self._stubs: - self._stubs['list_deployments'] = self._logged_channel.unary_unary( - '/google.cloud.config.v1.Config/ListDeployments', - request_serializer=config.ListDeploymentsRequest.serialize, - response_deserializer=config.ListDeploymentsResponse.deserialize, - ) - return self._stubs['list_deployments'] - - @property - def get_deployment(self) -> Callable[ - [config.GetDeploymentRequest], - Awaitable[config.Deployment]]: - r"""Return a callable for the get deployment method over gRPC. - - Gets details about a - [Deployment][google.cloud.config.v1.Deployment]. - - Returns: - Callable[[~.GetDeploymentRequest], - Awaitable[~.Deployment]]: - 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_deployment' not in self._stubs: - self._stubs['get_deployment'] = self._logged_channel.unary_unary( - '/google.cloud.config.v1.Config/GetDeployment', - request_serializer=config.GetDeploymentRequest.serialize, - response_deserializer=config.Deployment.deserialize, - ) - return self._stubs['get_deployment'] - - @property - def create_deployment(self) -> Callable[ - [config.CreateDeploymentRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the create deployment method over gRPC. - - Creates a [Deployment][google.cloud.config.v1.Deployment]. - - Returns: - Callable[[~.CreateDeploymentRequest], - 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_deployment' not in self._stubs: - self._stubs['create_deployment'] = self._logged_channel.unary_unary( - '/google.cloud.config.v1.Config/CreateDeployment', - request_serializer=config.CreateDeploymentRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_deployment'] - - @property - def update_deployment(self) -> Callable[ - [config.UpdateDeploymentRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the update deployment method over gRPC. - - Updates a [Deployment][google.cloud.config.v1.Deployment]. - - Returns: - Callable[[~.UpdateDeploymentRequest], - 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_deployment' not in self._stubs: - self._stubs['update_deployment'] = self._logged_channel.unary_unary( - '/google.cloud.config.v1.Config/UpdateDeployment', - request_serializer=config.UpdateDeploymentRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_deployment'] - - @property - def delete_deployment(self) -> Callable[ - [config.DeleteDeploymentRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the delete deployment method over gRPC. - - Deletes a [Deployment][google.cloud.config.v1.Deployment]. - - Returns: - Callable[[~.DeleteDeploymentRequest], - 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_deployment' not in self._stubs: - self._stubs['delete_deployment'] = self._logged_channel.unary_unary( - '/google.cloud.config.v1.Config/DeleteDeployment', - request_serializer=config.DeleteDeploymentRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_deployment'] - - @property - def list_revisions(self) -> Callable[ - [config.ListRevisionsRequest], - Awaitable[config.ListRevisionsResponse]]: - r"""Return a callable for the list revisions method over gRPC. - - Lists [Revision][google.cloud.config.v1.Revision]s of a - deployment. - - Returns: - Callable[[~.ListRevisionsRequest], - Awaitable[~.ListRevisionsResponse]]: - 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_revisions' not in self._stubs: - self._stubs['list_revisions'] = self._logged_channel.unary_unary( - '/google.cloud.config.v1.Config/ListRevisions', - request_serializer=config.ListRevisionsRequest.serialize, - response_deserializer=config.ListRevisionsResponse.deserialize, - ) - return self._stubs['list_revisions'] - - @property - def get_revision(self) -> Callable[ - [config.GetRevisionRequest], - Awaitable[config.Revision]]: - r"""Return a callable for the get revision method over gRPC. - - Gets details about a - [Revision][google.cloud.config.v1.Revision]. - - Returns: - Callable[[~.GetRevisionRequest], - Awaitable[~.Revision]]: - 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_revision' not in self._stubs: - self._stubs['get_revision'] = self._logged_channel.unary_unary( - '/google.cloud.config.v1.Config/GetRevision', - request_serializer=config.GetRevisionRequest.serialize, - response_deserializer=config.Revision.deserialize, - ) - return self._stubs['get_revision'] - - @property - def get_resource(self) -> Callable[ - [config.GetResourceRequest], - Awaitable[config.Resource]]: - r"""Return a callable for the get resource method over gRPC. - - Gets details about a [Resource][google.cloud.config.v1.Resource] - deployed by Infra Manager. - - Returns: - Callable[[~.GetResourceRequest], - Awaitable[~.Resource]]: - 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_resource' not in self._stubs: - self._stubs['get_resource'] = self._logged_channel.unary_unary( - '/google.cloud.config.v1.Config/GetResource', - request_serializer=config.GetResourceRequest.serialize, - response_deserializer=config.Resource.deserialize, - ) - return self._stubs['get_resource'] - - @property - def list_resources(self) -> Callable[ - [config.ListResourcesRequest], - Awaitable[config.ListResourcesResponse]]: - r"""Return a callable for the list resources method over gRPC. - - Lists [Resources][google.cloud.config.v1.Resource] in a given - revision. - - Returns: - Callable[[~.ListResourcesRequest], - Awaitable[~.ListResourcesResponse]]: - 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_resources' not in self._stubs: - self._stubs['list_resources'] = self._logged_channel.unary_unary( - '/google.cloud.config.v1.Config/ListResources', - request_serializer=config.ListResourcesRequest.serialize, - response_deserializer=config.ListResourcesResponse.deserialize, - ) - return self._stubs['list_resources'] - - @property - def export_deployment_statefile(self) -> Callable[ - [config.ExportDeploymentStatefileRequest], - Awaitable[config.Statefile]]: - r"""Return a callable for the export deployment statefile method over gRPC. - - Exports Terraform state file from a given deployment. - - Returns: - Callable[[~.ExportDeploymentStatefileRequest], - Awaitable[~.Statefile]]: - 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 'export_deployment_statefile' not in self._stubs: - self._stubs['export_deployment_statefile'] = self._logged_channel.unary_unary( - '/google.cloud.config.v1.Config/ExportDeploymentStatefile', - request_serializer=config.ExportDeploymentStatefileRequest.serialize, - response_deserializer=config.Statefile.deserialize, - ) - return self._stubs['export_deployment_statefile'] - - @property - def export_revision_statefile(self) -> Callable[ - [config.ExportRevisionStatefileRequest], - Awaitable[config.Statefile]]: - r"""Return a callable for the export revision statefile method over gRPC. - - Exports Terraform state file from a given revision. - - Returns: - Callable[[~.ExportRevisionStatefileRequest], - Awaitable[~.Statefile]]: - 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 'export_revision_statefile' not in self._stubs: - self._stubs['export_revision_statefile'] = self._logged_channel.unary_unary( - '/google.cloud.config.v1.Config/ExportRevisionStatefile', - request_serializer=config.ExportRevisionStatefileRequest.serialize, - response_deserializer=config.Statefile.deserialize, - ) - return self._stubs['export_revision_statefile'] - - @property - def import_statefile(self) -> Callable[ - [config.ImportStatefileRequest], - Awaitable[config.Statefile]]: - r"""Return a callable for the import statefile method over gRPC. - - Imports Terraform state file in a given deployment. - The state file does not take effect until the Deployment - has been unlocked. - - Returns: - Callable[[~.ImportStatefileRequest], - Awaitable[~.Statefile]]: - 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 'import_statefile' not in self._stubs: - self._stubs['import_statefile'] = self._logged_channel.unary_unary( - '/google.cloud.config.v1.Config/ImportStatefile', - request_serializer=config.ImportStatefileRequest.serialize, - response_deserializer=config.Statefile.deserialize, - ) - return self._stubs['import_statefile'] - - @property - def delete_statefile(self) -> Callable[ - [config.DeleteStatefileRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete statefile method over gRPC. - - Deletes Terraform state file in a given deployment. - - Returns: - Callable[[~.DeleteStatefileRequest], - 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_statefile' not in self._stubs: - self._stubs['delete_statefile'] = self._logged_channel.unary_unary( - '/google.cloud.config.v1.Config/DeleteStatefile', - request_serializer=config.DeleteStatefileRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_statefile'] - - @property - def lock_deployment(self) -> Callable[ - [config.LockDeploymentRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the lock deployment method over gRPC. - - Locks a deployment. - - Returns: - Callable[[~.LockDeploymentRequest], - 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 'lock_deployment' not in self._stubs: - self._stubs['lock_deployment'] = self._logged_channel.unary_unary( - '/google.cloud.config.v1.Config/LockDeployment', - request_serializer=config.LockDeploymentRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['lock_deployment'] - - @property - def unlock_deployment(self) -> Callable[ - [config.UnlockDeploymentRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the unlock deployment method over gRPC. - - Unlocks a locked deployment. - - Returns: - Callable[[~.UnlockDeploymentRequest], - 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 'unlock_deployment' not in self._stubs: - self._stubs['unlock_deployment'] = self._logged_channel.unary_unary( - '/google.cloud.config.v1.Config/UnlockDeployment', - request_serializer=config.UnlockDeploymentRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['unlock_deployment'] - - @property - def export_lock_info(self) -> Callable[ - [config.ExportLockInfoRequest], - Awaitable[config.LockInfo]]: - r"""Return a callable for the export lock info method over gRPC. - - Exports the lock info on a locked deployment. - - Returns: - Callable[[~.ExportLockInfoRequest], - Awaitable[~.LockInfo]]: - 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 'export_lock_info' not in self._stubs: - self._stubs['export_lock_info'] = self._logged_channel.unary_unary( - '/google.cloud.config.v1.Config/ExportLockInfo', - request_serializer=config.ExportLockInfoRequest.serialize, - response_deserializer=config.LockInfo.deserialize, - ) - return self._stubs['export_lock_info'] - - @property - def create_preview(self) -> Callable[ - [config.CreatePreviewRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the create preview method over gRPC. - - Creates a [Preview][google.cloud.config.v1.Preview]. - - Returns: - Callable[[~.CreatePreviewRequest], - 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_preview' not in self._stubs: - self._stubs['create_preview'] = self._logged_channel.unary_unary( - '/google.cloud.config.v1.Config/CreatePreview', - request_serializer=config.CreatePreviewRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_preview'] - - @property - def get_preview(self) -> Callable[ - [config.GetPreviewRequest], - Awaitable[config.Preview]]: - r"""Return a callable for the get preview method over gRPC. - - Gets details about a [Preview][google.cloud.config.v1.Preview]. - - Returns: - Callable[[~.GetPreviewRequest], - Awaitable[~.Preview]]: - 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_preview' not in self._stubs: - self._stubs['get_preview'] = self._logged_channel.unary_unary( - '/google.cloud.config.v1.Config/GetPreview', - request_serializer=config.GetPreviewRequest.serialize, - response_deserializer=config.Preview.deserialize, - ) - return self._stubs['get_preview'] - - @property - def list_previews(self) -> Callable[ - [config.ListPreviewsRequest], - Awaitable[config.ListPreviewsResponse]]: - r"""Return a callable for the list previews method over gRPC. - - Lists [Preview][google.cloud.config.v1.Preview]s in a given - project and location. - - Returns: - Callable[[~.ListPreviewsRequest], - Awaitable[~.ListPreviewsResponse]]: - 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_previews' not in self._stubs: - self._stubs['list_previews'] = self._logged_channel.unary_unary( - '/google.cloud.config.v1.Config/ListPreviews', - request_serializer=config.ListPreviewsRequest.serialize, - response_deserializer=config.ListPreviewsResponse.deserialize, - ) - return self._stubs['list_previews'] - - @property - def delete_preview(self) -> Callable[ - [config.DeletePreviewRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the delete preview method over gRPC. - - Deletes a [Preview][google.cloud.config.v1.Preview]. - - Returns: - Callable[[~.DeletePreviewRequest], - 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_preview' not in self._stubs: - self._stubs['delete_preview'] = self._logged_channel.unary_unary( - '/google.cloud.config.v1.Config/DeletePreview', - request_serializer=config.DeletePreviewRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_preview'] - - @property - def export_preview_result(self) -> Callable[ - [config.ExportPreviewResultRequest], - Awaitable[config.ExportPreviewResultResponse]]: - r"""Return a callable for the export preview result method over gRPC. - - Export [Preview][google.cloud.config.v1.Preview] results. - - Returns: - Callable[[~.ExportPreviewResultRequest], - Awaitable[~.ExportPreviewResultResponse]]: - 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 'export_preview_result' not in self._stubs: - self._stubs['export_preview_result'] = self._logged_channel.unary_unary( - '/google.cloud.config.v1.Config/ExportPreviewResult', - request_serializer=config.ExportPreviewResultRequest.serialize, - response_deserializer=config.ExportPreviewResultResponse.deserialize, - ) - return self._stubs['export_preview_result'] - - @property - def list_terraform_versions(self) -> Callable[ - [config.ListTerraformVersionsRequest], - Awaitable[config.ListTerraformVersionsResponse]]: - r"""Return a callable for the list terraform versions method over gRPC. - - Lists - [TerraformVersion][google.cloud.config.v1.TerraformVersion]s in - a given project and location. - - Returns: - Callable[[~.ListTerraformVersionsRequest], - Awaitable[~.ListTerraformVersionsResponse]]: - 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_terraform_versions' not in self._stubs: - self._stubs['list_terraform_versions'] = self._logged_channel.unary_unary( - '/google.cloud.config.v1.Config/ListTerraformVersions', - request_serializer=config.ListTerraformVersionsRequest.serialize, - response_deserializer=config.ListTerraformVersionsResponse.deserialize, - ) - return self._stubs['list_terraform_versions'] - - @property - def get_terraform_version(self) -> Callable[ - [config.GetTerraformVersionRequest], - Awaitable[config.TerraformVersion]]: - r"""Return a callable for the get terraform version method over gRPC. - - Gets details about a - [TerraformVersion][google.cloud.config.v1.TerraformVersion]. - - Returns: - Callable[[~.GetTerraformVersionRequest], - Awaitable[~.TerraformVersion]]: - 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_terraform_version' not in self._stubs: - self._stubs['get_terraform_version'] = self._logged_channel.unary_unary( - '/google.cloud.config.v1.Config/GetTerraformVersion', - request_serializer=config.GetTerraformVersionRequest.serialize, - response_deserializer=config.TerraformVersion.deserialize, - ) - return self._stubs['get_terraform_version'] - - @property - def list_resource_changes(self) -> Callable[ - [config.ListResourceChangesRequest], - Awaitable[config.ListResourceChangesResponse]]: - r"""Return a callable for the list resource changes method over gRPC. - - Lists ResourceChanges for a given preview. - - Returns: - Callable[[~.ListResourceChangesRequest], - Awaitable[~.ListResourceChangesResponse]]: - 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_changes' not in self._stubs: - self._stubs['list_resource_changes'] = self._logged_channel.unary_unary( - '/google.cloud.config.v1.Config/ListResourceChanges', - request_serializer=config.ListResourceChangesRequest.serialize, - response_deserializer=config.ListResourceChangesResponse.deserialize, - ) - return self._stubs['list_resource_changes'] - - @property - def get_resource_change(self) -> Callable[ - [config.GetResourceChangeRequest], - Awaitable[config.ResourceChange]]: - r"""Return a callable for the get resource change method over gRPC. - - Get a ResourceChange for a given preview. - - Returns: - Callable[[~.GetResourceChangeRequest], - Awaitable[~.ResourceChange]]: - 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_resource_change' not in self._stubs: - self._stubs['get_resource_change'] = self._logged_channel.unary_unary( - '/google.cloud.config.v1.Config/GetResourceChange', - request_serializer=config.GetResourceChangeRequest.serialize, - response_deserializer=config.ResourceChange.deserialize, - ) - return self._stubs['get_resource_change'] - - @property - def list_resource_drifts(self) -> Callable[ - [config.ListResourceDriftsRequest], - Awaitable[config.ListResourceDriftsResponse]]: - r"""Return a callable for the list resource drifts method over gRPC. - - List ResourceDrifts for a given preview. - - Returns: - Callable[[~.ListResourceDriftsRequest], - Awaitable[~.ListResourceDriftsResponse]]: - 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_drifts' not in self._stubs: - self._stubs['list_resource_drifts'] = self._logged_channel.unary_unary( - '/google.cloud.config.v1.Config/ListResourceDrifts', - request_serializer=config.ListResourceDriftsRequest.serialize, - response_deserializer=config.ListResourceDriftsResponse.deserialize, - ) - return self._stubs['list_resource_drifts'] - - @property - def get_resource_drift(self) -> Callable[ - [config.GetResourceDriftRequest], - Awaitable[config.ResourceDrift]]: - r"""Return a callable for the get resource drift method over gRPC. - - Get a ResourceDrift for a given preview. - - Returns: - Callable[[~.GetResourceDriftRequest], - Awaitable[~.ResourceDrift]]: - 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_resource_drift' not in self._stubs: - self._stubs['get_resource_drift'] = self._logged_channel.unary_unary( - '/google.cloud.config.v1.Config/GetResourceDrift', - request_serializer=config.GetResourceDriftRequest.serialize, - response_deserializer=config.ResourceDrift.deserialize, - ) - return self._stubs['get_resource_drift'] - - 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_deployments: self._wrap_method( - self.list_deployments, - default_timeout=None, - client_info=client_info, - ), - self.get_deployment: self._wrap_method( - self.get_deployment, - default_timeout=None, - client_info=client_info, - ), - self.create_deployment: self._wrap_method( - self.create_deployment, - default_timeout=None, - client_info=client_info, - ), - self.update_deployment: self._wrap_method( - self.update_deployment, - default_timeout=None, - client_info=client_info, - ), - self.delete_deployment: self._wrap_method( - self.delete_deployment, - default_timeout=None, - client_info=client_info, - ), - self.list_revisions: self._wrap_method( - self.list_revisions, - default_timeout=None, - client_info=client_info, - ), - self.get_revision: self._wrap_method( - self.get_revision, - default_timeout=None, - client_info=client_info, - ), - self.get_resource: self._wrap_method( - self.get_resource, - default_timeout=None, - client_info=client_info, - ), - self.list_resources: self._wrap_method( - self.list_resources, - default_timeout=None, - client_info=client_info, - ), - self.export_deployment_statefile: self._wrap_method( - self.export_deployment_statefile, - default_timeout=None, - client_info=client_info, - ), - self.export_revision_statefile: self._wrap_method( - self.export_revision_statefile, - default_timeout=None, - client_info=client_info, - ), - self.import_statefile: self._wrap_method( - self.import_statefile, - default_timeout=None, - client_info=client_info, - ), - self.delete_statefile: self._wrap_method( - self.delete_statefile, - default_timeout=None, - client_info=client_info, - ), - self.lock_deployment: self._wrap_method( - self.lock_deployment, - default_timeout=None, - client_info=client_info, - ), - self.unlock_deployment: self._wrap_method( - self.unlock_deployment, - default_timeout=None, - client_info=client_info, - ), - self.export_lock_info: self._wrap_method( - self.export_lock_info, - default_timeout=None, - client_info=client_info, - ), - self.create_preview: self._wrap_method( - self.create_preview, - default_timeout=None, - client_info=client_info, - ), - self.get_preview: self._wrap_method( - self.get_preview, - default_timeout=None, - client_info=client_info, - ), - self.list_previews: self._wrap_method( - self.list_previews, - default_timeout=None, - client_info=client_info, - ), - self.delete_preview: self._wrap_method( - self.delete_preview, - default_timeout=None, - client_info=client_info, - ), - self.export_preview_result: self._wrap_method( - self.export_preview_result, - default_timeout=None, - client_info=client_info, - ), - self.list_terraform_versions: self._wrap_method( - self.list_terraform_versions, - default_timeout=None, - client_info=client_info, - ), - self.get_terraform_version: self._wrap_method( - self.get_terraform_version, - default_timeout=None, - client_info=client_info, - ), - self.list_resource_changes: self._wrap_method( - self.list_resource_changes, - default_timeout=None, - client_info=client_info, - ), - self.get_resource_change: self._wrap_method( - self.get_resource_change, - default_timeout=None, - client_info=client_info, - ), - self.list_resource_drifts: self._wrap_method( - self.list_resource_drifts, - default_timeout=None, - client_info=client_info, - ), - self.get_resource_drift: self._wrap_method( - self.get_resource_drift, - 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__ = ( - 'ConfigGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/transports/rest.py b/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/transports/rest.py deleted file mode 100644 index 1ce4c3930e23..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/transports/rest.py +++ /dev/null @@ -1,6103 +0,0 @@ -# -*- 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. -# -import logging -import json # type: ignore - -from google.auth.transport.requests import AuthorizedSession # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import gapic_v1 -import google.protobuf - -from google.protobuf import json_format -from google.api_core import operations_v1 -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.cloud.location import locations_pb2 # type: ignore - -from requests import __version__ as requests_version -import dataclasses -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - - -from google.cloud.config_v1.types import config -from google.protobuf import empty_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore - - -from .rest_base import _BaseConfigRestTransport -from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - -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}", -) - -if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER - DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ - - -class ConfigRestInterceptor: - """Interceptor for Config. - - 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 ConfigRestTransport. - - .. code-block:: python - class MyCustomConfigInterceptor(ConfigRestInterceptor): - def pre_create_deployment(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_deployment(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_preview(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_preview(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_deployment(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_delete_deployment(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_preview(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_delete_preview(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_statefile(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def pre_export_deployment_statefile(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_export_deployment_statefile(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_export_lock_info(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_export_lock_info(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_export_preview_result(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_export_preview_result(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_export_revision_statefile(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_export_revision_statefile(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_deployment(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_deployment(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_preview(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_preview(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_resource(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_resource(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_resource_change(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_resource_change(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_resource_drift(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_resource_drift(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_revision(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_revision(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_terraform_version(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_terraform_version(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_import_statefile(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_import_statefile(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_deployments(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_deployments(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_previews(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_previews(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_resource_changes(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_resource_changes(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_resource_drifts(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_resource_drifts(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_resources(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_resources(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_revisions(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_revisions(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_terraform_versions(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_terraform_versions(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_lock_deployment(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_lock_deployment(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_unlock_deployment(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_unlock_deployment(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_deployment(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_deployment(self, response): - logging.log(f"Received response: {response}") - return response - - transport = ConfigRestTransport(interceptor=MyCustomConfigInterceptor()) - client = ConfigClient(transport=transport) - - - """ - def pre_create_deployment(self, request: config.CreateDeploymentRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[config.CreateDeploymentRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for create_deployment - - Override in a subclass to manipulate the request or metadata - before they are sent to the Config server. - """ - return request, metadata - - def post_create_deployment(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for create_deployment - - DEPRECATED. Please use the `post_create_deployment_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Config server but before - it is returned to user code. This `post_create_deployment` interceptor runs - before the `post_create_deployment_with_metadata` interceptor. - """ - return response - - def post_create_deployment_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_deployment - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Config server but before it is returned to user code. - - We recommend only using this `post_create_deployment_with_metadata` - interceptor in new development instead of the `post_create_deployment` interceptor. - When both interceptors are used, this `post_create_deployment_with_metadata` interceptor runs after the - `post_create_deployment` interceptor. The (possibly modified) response returned by - `post_create_deployment` will be passed to - `post_create_deployment_with_metadata`. - """ - return response, metadata - - def pre_create_preview(self, request: config.CreatePreviewRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[config.CreatePreviewRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for create_preview - - Override in a subclass to manipulate the request or metadata - before they are sent to the Config server. - """ - return request, metadata - - def post_create_preview(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for create_preview - - DEPRECATED. Please use the `post_create_preview_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Config server but before - it is returned to user code. This `post_create_preview` interceptor runs - before the `post_create_preview_with_metadata` interceptor. - """ - return response - - def post_create_preview_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_preview - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Config server but before it is returned to user code. - - We recommend only using this `post_create_preview_with_metadata` - interceptor in new development instead of the `post_create_preview` interceptor. - When both interceptors are used, this `post_create_preview_with_metadata` interceptor runs after the - `post_create_preview` interceptor. The (possibly modified) response returned by - `post_create_preview` will be passed to - `post_create_preview_with_metadata`. - """ - return response, metadata - - def pre_delete_deployment(self, request: config.DeleteDeploymentRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[config.DeleteDeploymentRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for delete_deployment - - Override in a subclass to manipulate the request or metadata - before they are sent to the Config server. - """ - return request, metadata - - def post_delete_deployment(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for delete_deployment - - DEPRECATED. Please use the `post_delete_deployment_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Config server but before - it is returned to user code. This `post_delete_deployment` interceptor runs - before the `post_delete_deployment_with_metadata` interceptor. - """ - return response - - def post_delete_deployment_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_deployment - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Config server but before it is returned to user code. - - We recommend only using this `post_delete_deployment_with_metadata` - interceptor in new development instead of the `post_delete_deployment` interceptor. - When both interceptors are used, this `post_delete_deployment_with_metadata` interceptor runs after the - `post_delete_deployment` interceptor. The (possibly modified) response returned by - `post_delete_deployment` will be passed to - `post_delete_deployment_with_metadata`. - """ - return response, metadata - - def pre_delete_preview(self, request: config.DeletePreviewRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[config.DeletePreviewRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for delete_preview - - Override in a subclass to manipulate the request or metadata - before they are sent to the Config server. - """ - return request, metadata - - def post_delete_preview(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for delete_preview - - DEPRECATED. Please use the `post_delete_preview_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Config server but before - it is returned to user code. This `post_delete_preview` interceptor runs - before the `post_delete_preview_with_metadata` interceptor. - """ - return response - - def post_delete_preview_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_preview - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Config server but before it is returned to user code. - - We recommend only using this `post_delete_preview_with_metadata` - interceptor in new development instead of the `post_delete_preview` interceptor. - When both interceptors are used, this `post_delete_preview_with_metadata` interceptor runs after the - `post_delete_preview` interceptor. The (possibly modified) response returned by - `post_delete_preview` will be passed to - `post_delete_preview_with_metadata`. - """ - return response, metadata - - def pre_delete_statefile(self, request: config.DeleteStatefileRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[config.DeleteStatefileRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for delete_statefile - - Override in a subclass to manipulate the request or metadata - before they are sent to the Config server. - """ - return request, metadata - - def pre_export_deployment_statefile(self, request: config.ExportDeploymentStatefileRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[config.ExportDeploymentStatefileRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for export_deployment_statefile - - Override in a subclass to manipulate the request or metadata - before they are sent to the Config server. - """ - return request, metadata - - def post_export_deployment_statefile(self, response: config.Statefile) -> config.Statefile: - """Post-rpc interceptor for export_deployment_statefile - - DEPRECATED. Please use the `post_export_deployment_statefile_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Config server but before - it is returned to user code. This `post_export_deployment_statefile` interceptor runs - before the `post_export_deployment_statefile_with_metadata` interceptor. - """ - return response - - def post_export_deployment_statefile_with_metadata(self, response: config.Statefile, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[config.Statefile, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for export_deployment_statefile - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Config server but before it is returned to user code. - - We recommend only using this `post_export_deployment_statefile_with_metadata` - interceptor in new development instead of the `post_export_deployment_statefile` interceptor. - When both interceptors are used, this `post_export_deployment_statefile_with_metadata` interceptor runs after the - `post_export_deployment_statefile` interceptor. The (possibly modified) response returned by - `post_export_deployment_statefile` will be passed to - `post_export_deployment_statefile_with_metadata`. - """ - return response, metadata - - def pre_export_lock_info(self, request: config.ExportLockInfoRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[config.ExportLockInfoRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for export_lock_info - - Override in a subclass to manipulate the request or metadata - before they are sent to the Config server. - """ - return request, metadata - - def post_export_lock_info(self, response: config.LockInfo) -> config.LockInfo: - """Post-rpc interceptor for export_lock_info - - DEPRECATED. Please use the `post_export_lock_info_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Config server but before - it is returned to user code. This `post_export_lock_info` interceptor runs - before the `post_export_lock_info_with_metadata` interceptor. - """ - return response - - def post_export_lock_info_with_metadata(self, response: config.LockInfo, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[config.LockInfo, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for export_lock_info - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Config server but before it is returned to user code. - - We recommend only using this `post_export_lock_info_with_metadata` - interceptor in new development instead of the `post_export_lock_info` interceptor. - When both interceptors are used, this `post_export_lock_info_with_metadata` interceptor runs after the - `post_export_lock_info` interceptor. The (possibly modified) response returned by - `post_export_lock_info` will be passed to - `post_export_lock_info_with_metadata`. - """ - return response, metadata - - def pre_export_preview_result(self, request: config.ExportPreviewResultRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[config.ExportPreviewResultRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for export_preview_result - - Override in a subclass to manipulate the request or metadata - before they are sent to the Config server. - """ - return request, metadata - - def post_export_preview_result(self, response: config.ExportPreviewResultResponse) -> config.ExportPreviewResultResponse: - """Post-rpc interceptor for export_preview_result - - DEPRECATED. Please use the `post_export_preview_result_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Config server but before - it is returned to user code. This `post_export_preview_result` interceptor runs - before the `post_export_preview_result_with_metadata` interceptor. - """ - return response - - def post_export_preview_result_with_metadata(self, response: config.ExportPreviewResultResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[config.ExportPreviewResultResponse, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for export_preview_result - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Config server but before it is returned to user code. - - We recommend only using this `post_export_preview_result_with_metadata` - interceptor in new development instead of the `post_export_preview_result` interceptor. - When both interceptors are used, this `post_export_preview_result_with_metadata` interceptor runs after the - `post_export_preview_result` interceptor. The (possibly modified) response returned by - `post_export_preview_result` will be passed to - `post_export_preview_result_with_metadata`. - """ - return response, metadata - - def pre_export_revision_statefile(self, request: config.ExportRevisionStatefileRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[config.ExportRevisionStatefileRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for export_revision_statefile - - Override in a subclass to manipulate the request or metadata - before they are sent to the Config server. - """ - return request, metadata - - def post_export_revision_statefile(self, response: config.Statefile) -> config.Statefile: - """Post-rpc interceptor for export_revision_statefile - - DEPRECATED. Please use the `post_export_revision_statefile_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Config server but before - it is returned to user code. This `post_export_revision_statefile` interceptor runs - before the `post_export_revision_statefile_with_metadata` interceptor. - """ - return response - - def post_export_revision_statefile_with_metadata(self, response: config.Statefile, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[config.Statefile, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for export_revision_statefile - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Config server but before it is returned to user code. - - We recommend only using this `post_export_revision_statefile_with_metadata` - interceptor in new development instead of the `post_export_revision_statefile` interceptor. - When both interceptors are used, this `post_export_revision_statefile_with_metadata` interceptor runs after the - `post_export_revision_statefile` interceptor. The (possibly modified) response returned by - `post_export_revision_statefile` will be passed to - `post_export_revision_statefile_with_metadata`. - """ - return response, metadata - - def pre_get_deployment(self, request: config.GetDeploymentRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[config.GetDeploymentRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for get_deployment - - Override in a subclass to manipulate the request or metadata - before they are sent to the Config server. - """ - return request, metadata - - def post_get_deployment(self, response: config.Deployment) -> config.Deployment: - """Post-rpc interceptor for get_deployment - - DEPRECATED. Please use the `post_get_deployment_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Config server but before - it is returned to user code. This `post_get_deployment` interceptor runs - before the `post_get_deployment_with_metadata` interceptor. - """ - return response - - def post_get_deployment_with_metadata(self, response: config.Deployment, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[config.Deployment, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for get_deployment - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Config server but before it is returned to user code. - - We recommend only using this `post_get_deployment_with_metadata` - interceptor in new development instead of the `post_get_deployment` interceptor. - When both interceptors are used, this `post_get_deployment_with_metadata` interceptor runs after the - `post_get_deployment` interceptor. The (possibly modified) response returned by - `post_get_deployment` will be passed to - `post_get_deployment_with_metadata`. - """ - return response, metadata - - def pre_get_preview(self, request: config.GetPreviewRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[config.GetPreviewRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for get_preview - - Override in a subclass to manipulate the request or metadata - before they are sent to the Config server. - """ - return request, metadata - - def post_get_preview(self, response: config.Preview) -> config.Preview: - """Post-rpc interceptor for get_preview - - DEPRECATED. Please use the `post_get_preview_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Config server but before - it is returned to user code. This `post_get_preview` interceptor runs - before the `post_get_preview_with_metadata` interceptor. - """ - return response - - def post_get_preview_with_metadata(self, response: config.Preview, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[config.Preview, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for get_preview - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Config server but before it is returned to user code. - - We recommend only using this `post_get_preview_with_metadata` - interceptor in new development instead of the `post_get_preview` interceptor. - When both interceptors are used, this `post_get_preview_with_metadata` interceptor runs after the - `post_get_preview` interceptor. The (possibly modified) response returned by - `post_get_preview` will be passed to - `post_get_preview_with_metadata`. - """ - return response, metadata - - def pre_get_resource(self, request: config.GetResourceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[config.GetResourceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for get_resource - - Override in a subclass to manipulate the request or metadata - before they are sent to the Config server. - """ - return request, metadata - - def post_get_resource(self, response: config.Resource) -> config.Resource: - """Post-rpc interceptor for get_resource - - DEPRECATED. Please use the `post_get_resource_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Config server but before - it is returned to user code. This `post_get_resource` interceptor runs - before the `post_get_resource_with_metadata` interceptor. - """ - return response - - def post_get_resource_with_metadata(self, response: config.Resource, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[config.Resource, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for get_resource - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Config server but before it is returned to user code. - - We recommend only using this `post_get_resource_with_metadata` - interceptor in new development instead of the `post_get_resource` interceptor. - When both interceptors are used, this `post_get_resource_with_metadata` interceptor runs after the - `post_get_resource` interceptor. The (possibly modified) response returned by - `post_get_resource` will be passed to - `post_get_resource_with_metadata`. - """ - return response, metadata - - def pre_get_resource_change(self, request: config.GetResourceChangeRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[config.GetResourceChangeRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for get_resource_change - - Override in a subclass to manipulate the request or metadata - before they are sent to the Config server. - """ - return request, metadata - - def post_get_resource_change(self, response: config.ResourceChange) -> config.ResourceChange: - """Post-rpc interceptor for get_resource_change - - DEPRECATED. Please use the `post_get_resource_change_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Config server but before - it is returned to user code. This `post_get_resource_change` interceptor runs - before the `post_get_resource_change_with_metadata` interceptor. - """ - return response - - def post_get_resource_change_with_metadata(self, response: config.ResourceChange, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[config.ResourceChange, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for get_resource_change - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Config server but before it is returned to user code. - - We recommend only using this `post_get_resource_change_with_metadata` - interceptor in new development instead of the `post_get_resource_change` interceptor. - When both interceptors are used, this `post_get_resource_change_with_metadata` interceptor runs after the - `post_get_resource_change` interceptor. The (possibly modified) response returned by - `post_get_resource_change` will be passed to - `post_get_resource_change_with_metadata`. - """ - return response, metadata - - def pre_get_resource_drift(self, request: config.GetResourceDriftRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[config.GetResourceDriftRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for get_resource_drift - - Override in a subclass to manipulate the request or metadata - before they are sent to the Config server. - """ - return request, metadata - - def post_get_resource_drift(self, response: config.ResourceDrift) -> config.ResourceDrift: - """Post-rpc interceptor for get_resource_drift - - DEPRECATED. Please use the `post_get_resource_drift_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Config server but before - it is returned to user code. This `post_get_resource_drift` interceptor runs - before the `post_get_resource_drift_with_metadata` interceptor. - """ - return response - - def post_get_resource_drift_with_metadata(self, response: config.ResourceDrift, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[config.ResourceDrift, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for get_resource_drift - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Config server but before it is returned to user code. - - We recommend only using this `post_get_resource_drift_with_metadata` - interceptor in new development instead of the `post_get_resource_drift` interceptor. - When both interceptors are used, this `post_get_resource_drift_with_metadata` interceptor runs after the - `post_get_resource_drift` interceptor. The (possibly modified) response returned by - `post_get_resource_drift` will be passed to - `post_get_resource_drift_with_metadata`. - """ - return response, metadata - - def pre_get_revision(self, request: config.GetRevisionRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[config.GetRevisionRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for get_revision - - Override in a subclass to manipulate the request or metadata - before they are sent to the Config server. - """ - return request, metadata - - def post_get_revision(self, response: config.Revision) -> config.Revision: - """Post-rpc interceptor for get_revision - - DEPRECATED. Please use the `post_get_revision_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Config server but before - it is returned to user code. This `post_get_revision` interceptor runs - before the `post_get_revision_with_metadata` interceptor. - """ - return response - - def post_get_revision_with_metadata(self, response: config.Revision, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[config.Revision, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for get_revision - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Config server but before it is returned to user code. - - We recommend only using this `post_get_revision_with_metadata` - interceptor in new development instead of the `post_get_revision` interceptor. - When both interceptors are used, this `post_get_revision_with_metadata` interceptor runs after the - `post_get_revision` interceptor. The (possibly modified) response returned by - `post_get_revision` will be passed to - `post_get_revision_with_metadata`. - """ - return response, metadata - - def pre_get_terraform_version(self, request: config.GetTerraformVersionRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[config.GetTerraformVersionRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for get_terraform_version - - Override in a subclass to manipulate the request or metadata - before they are sent to the Config server. - """ - return request, metadata - - def post_get_terraform_version(self, response: config.TerraformVersion) -> config.TerraformVersion: - """Post-rpc interceptor for get_terraform_version - - DEPRECATED. Please use the `post_get_terraform_version_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Config server but before - it is returned to user code. This `post_get_terraform_version` interceptor runs - before the `post_get_terraform_version_with_metadata` interceptor. - """ - return response - - def post_get_terraform_version_with_metadata(self, response: config.TerraformVersion, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[config.TerraformVersion, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for get_terraform_version - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Config server but before it is returned to user code. - - We recommend only using this `post_get_terraform_version_with_metadata` - interceptor in new development instead of the `post_get_terraform_version` interceptor. - When both interceptors are used, this `post_get_terraform_version_with_metadata` interceptor runs after the - `post_get_terraform_version` interceptor. The (possibly modified) response returned by - `post_get_terraform_version` will be passed to - `post_get_terraform_version_with_metadata`. - """ - return response, metadata - - def pre_import_statefile(self, request: config.ImportStatefileRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[config.ImportStatefileRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for import_statefile - - Override in a subclass to manipulate the request or metadata - before they are sent to the Config server. - """ - return request, metadata - - def post_import_statefile(self, response: config.Statefile) -> config.Statefile: - """Post-rpc interceptor for import_statefile - - DEPRECATED. Please use the `post_import_statefile_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Config server but before - it is returned to user code. This `post_import_statefile` interceptor runs - before the `post_import_statefile_with_metadata` interceptor. - """ - return response - - def post_import_statefile_with_metadata(self, response: config.Statefile, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[config.Statefile, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for import_statefile - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Config server but before it is returned to user code. - - We recommend only using this `post_import_statefile_with_metadata` - interceptor in new development instead of the `post_import_statefile` interceptor. - When both interceptors are used, this `post_import_statefile_with_metadata` interceptor runs after the - `post_import_statefile` interceptor. The (possibly modified) response returned by - `post_import_statefile` will be passed to - `post_import_statefile_with_metadata`. - """ - return response, metadata - - def pre_list_deployments(self, request: config.ListDeploymentsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[config.ListDeploymentsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for list_deployments - - Override in a subclass to manipulate the request or metadata - before they are sent to the Config server. - """ - return request, metadata - - def post_list_deployments(self, response: config.ListDeploymentsResponse) -> config.ListDeploymentsResponse: - """Post-rpc interceptor for list_deployments - - DEPRECATED. Please use the `post_list_deployments_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Config server but before - it is returned to user code. This `post_list_deployments` interceptor runs - before the `post_list_deployments_with_metadata` interceptor. - """ - return response - - def post_list_deployments_with_metadata(self, response: config.ListDeploymentsResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[config.ListDeploymentsResponse, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for list_deployments - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Config server but before it is returned to user code. - - We recommend only using this `post_list_deployments_with_metadata` - interceptor in new development instead of the `post_list_deployments` interceptor. - When both interceptors are used, this `post_list_deployments_with_metadata` interceptor runs after the - `post_list_deployments` interceptor. The (possibly modified) response returned by - `post_list_deployments` will be passed to - `post_list_deployments_with_metadata`. - """ - return response, metadata - - def pre_list_previews(self, request: config.ListPreviewsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[config.ListPreviewsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for list_previews - - Override in a subclass to manipulate the request or metadata - before they are sent to the Config server. - """ - return request, metadata - - def post_list_previews(self, response: config.ListPreviewsResponse) -> config.ListPreviewsResponse: - """Post-rpc interceptor for list_previews - - DEPRECATED. Please use the `post_list_previews_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Config server but before - it is returned to user code. This `post_list_previews` interceptor runs - before the `post_list_previews_with_metadata` interceptor. - """ - return response - - def post_list_previews_with_metadata(self, response: config.ListPreviewsResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[config.ListPreviewsResponse, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for list_previews - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Config server but before it is returned to user code. - - We recommend only using this `post_list_previews_with_metadata` - interceptor in new development instead of the `post_list_previews` interceptor. - When both interceptors are used, this `post_list_previews_with_metadata` interceptor runs after the - `post_list_previews` interceptor. The (possibly modified) response returned by - `post_list_previews` will be passed to - `post_list_previews_with_metadata`. - """ - return response, metadata - - def pre_list_resource_changes(self, request: config.ListResourceChangesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[config.ListResourceChangesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for list_resource_changes - - Override in a subclass to manipulate the request or metadata - before they are sent to the Config server. - """ - return request, metadata - - def post_list_resource_changes(self, response: config.ListResourceChangesResponse) -> config.ListResourceChangesResponse: - """Post-rpc interceptor for list_resource_changes - - DEPRECATED. Please use the `post_list_resource_changes_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Config server but before - it is returned to user code. This `post_list_resource_changes` interceptor runs - before the `post_list_resource_changes_with_metadata` interceptor. - """ - return response - - def post_list_resource_changes_with_metadata(self, response: config.ListResourceChangesResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[config.ListResourceChangesResponse, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for list_resource_changes - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Config server but before it is returned to user code. - - We recommend only using this `post_list_resource_changes_with_metadata` - interceptor in new development instead of the `post_list_resource_changes` interceptor. - When both interceptors are used, this `post_list_resource_changes_with_metadata` interceptor runs after the - `post_list_resource_changes` interceptor. The (possibly modified) response returned by - `post_list_resource_changes` will be passed to - `post_list_resource_changes_with_metadata`. - """ - return response, metadata - - def pre_list_resource_drifts(self, request: config.ListResourceDriftsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[config.ListResourceDriftsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for list_resource_drifts - - Override in a subclass to manipulate the request or metadata - before they are sent to the Config server. - """ - return request, metadata - - def post_list_resource_drifts(self, response: config.ListResourceDriftsResponse) -> config.ListResourceDriftsResponse: - """Post-rpc interceptor for list_resource_drifts - - DEPRECATED. Please use the `post_list_resource_drifts_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Config server but before - it is returned to user code. This `post_list_resource_drifts` interceptor runs - before the `post_list_resource_drifts_with_metadata` interceptor. - """ - return response - - def post_list_resource_drifts_with_metadata(self, response: config.ListResourceDriftsResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[config.ListResourceDriftsResponse, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for list_resource_drifts - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Config server but before it is returned to user code. - - We recommend only using this `post_list_resource_drifts_with_metadata` - interceptor in new development instead of the `post_list_resource_drifts` interceptor. - When both interceptors are used, this `post_list_resource_drifts_with_metadata` interceptor runs after the - `post_list_resource_drifts` interceptor. The (possibly modified) response returned by - `post_list_resource_drifts` will be passed to - `post_list_resource_drifts_with_metadata`. - """ - return response, metadata - - def pre_list_resources(self, request: config.ListResourcesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[config.ListResourcesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for list_resources - - Override in a subclass to manipulate the request or metadata - before they are sent to the Config server. - """ - return request, metadata - - def post_list_resources(self, response: config.ListResourcesResponse) -> config.ListResourcesResponse: - """Post-rpc interceptor for list_resources - - DEPRECATED. Please use the `post_list_resources_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Config server but before - it is returned to user code. This `post_list_resources` interceptor runs - before the `post_list_resources_with_metadata` interceptor. - """ - return response - - def post_list_resources_with_metadata(self, response: config.ListResourcesResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[config.ListResourcesResponse, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for list_resources - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Config server but before it is returned to user code. - - We recommend only using this `post_list_resources_with_metadata` - interceptor in new development instead of the `post_list_resources` interceptor. - When both interceptors are used, this `post_list_resources_with_metadata` interceptor runs after the - `post_list_resources` interceptor. The (possibly modified) response returned by - `post_list_resources` will be passed to - `post_list_resources_with_metadata`. - """ - return response, metadata - - def pre_list_revisions(self, request: config.ListRevisionsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[config.ListRevisionsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for list_revisions - - Override in a subclass to manipulate the request or metadata - before they are sent to the Config server. - """ - return request, metadata - - def post_list_revisions(self, response: config.ListRevisionsResponse) -> config.ListRevisionsResponse: - """Post-rpc interceptor for list_revisions - - DEPRECATED. Please use the `post_list_revisions_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Config server but before - it is returned to user code. This `post_list_revisions` interceptor runs - before the `post_list_revisions_with_metadata` interceptor. - """ - return response - - def post_list_revisions_with_metadata(self, response: config.ListRevisionsResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[config.ListRevisionsResponse, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for list_revisions - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Config server but before it is returned to user code. - - We recommend only using this `post_list_revisions_with_metadata` - interceptor in new development instead of the `post_list_revisions` interceptor. - When both interceptors are used, this `post_list_revisions_with_metadata` interceptor runs after the - `post_list_revisions` interceptor. The (possibly modified) response returned by - `post_list_revisions` will be passed to - `post_list_revisions_with_metadata`. - """ - return response, metadata - - def pre_list_terraform_versions(self, request: config.ListTerraformVersionsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[config.ListTerraformVersionsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for list_terraform_versions - - Override in a subclass to manipulate the request or metadata - before they are sent to the Config server. - """ - return request, metadata - - def post_list_terraform_versions(self, response: config.ListTerraformVersionsResponse) -> config.ListTerraformVersionsResponse: - """Post-rpc interceptor for list_terraform_versions - - DEPRECATED. Please use the `post_list_terraform_versions_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Config server but before - it is returned to user code. This `post_list_terraform_versions` interceptor runs - before the `post_list_terraform_versions_with_metadata` interceptor. - """ - return response - - def post_list_terraform_versions_with_metadata(self, response: config.ListTerraformVersionsResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[config.ListTerraformVersionsResponse, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for list_terraform_versions - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Config server but before it is returned to user code. - - We recommend only using this `post_list_terraform_versions_with_metadata` - interceptor in new development instead of the `post_list_terraform_versions` interceptor. - When both interceptors are used, this `post_list_terraform_versions_with_metadata` interceptor runs after the - `post_list_terraform_versions` interceptor. The (possibly modified) response returned by - `post_list_terraform_versions` will be passed to - `post_list_terraform_versions_with_metadata`. - """ - return response, metadata - - def pre_lock_deployment(self, request: config.LockDeploymentRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[config.LockDeploymentRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for lock_deployment - - Override in a subclass to manipulate the request or metadata - before they are sent to the Config server. - """ - return request, metadata - - def post_lock_deployment(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for lock_deployment - - DEPRECATED. Please use the `post_lock_deployment_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Config server but before - it is returned to user code. This `post_lock_deployment` interceptor runs - before the `post_lock_deployment_with_metadata` interceptor. - """ - return response - - def post_lock_deployment_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 lock_deployment - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Config server but before it is returned to user code. - - We recommend only using this `post_lock_deployment_with_metadata` - interceptor in new development instead of the `post_lock_deployment` interceptor. - When both interceptors are used, this `post_lock_deployment_with_metadata` interceptor runs after the - `post_lock_deployment` interceptor. The (possibly modified) response returned by - `post_lock_deployment` will be passed to - `post_lock_deployment_with_metadata`. - """ - return response, metadata - - def pre_unlock_deployment(self, request: config.UnlockDeploymentRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[config.UnlockDeploymentRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for unlock_deployment - - Override in a subclass to manipulate the request or metadata - before they are sent to the Config server. - """ - return request, metadata - - def post_unlock_deployment(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for unlock_deployment - - DEPRECATED. Please use the `post_unlock_deployment_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Config server but before - it is returned to user code. This `post_unlock_deployment` interceptor runs - before the `post_unlock_deployment_with_metadata` interceptor. - """ - return response - - def post_unlock_deployment_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 unlock_deployment - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Config server but before it is returned to user code. - - We recommend only using this `post_unlock_deployment_with_metadata` - interceptor in new development instead of the `post_unlock_deployment` interceptor. - When both interceptors are used, this `post_unlock_deployment_with_metadata` interceptor runs after the - `post_unlock_deployment` interceptor. The (possibly modified) response returned by - `post_unlock_deployment` will be passed to - `post_unlock_deployment_with_metadata`. - """ - return response, metadata - - def pre_update_deployment(self, request: config.UpdateDeploymentRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[config.UpdateDeploymentRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for update_deployment - - Override in a subclass to manipulate the request or metadata - before they are sent to the Config server. - """ - return request, metadata - - def post_update_deployment(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for update_deployment - - DEPRECATED. Please use the `post_update_deployment_with_metadata` - interceptor instead. - - Override in a subclass to read or manipulate the response - after it is returned by the Config server but before - it is returned to user code. This `post_update_deployment` interceptor runs - before the `post_update_deployment_with_metadata` interceptor. - """ - return response - - def post_update_deployment_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_deployment - - Override in a subclass to read or manipulate the response or metadata after it - is returned by the Config server but before it is returned to user code. - - We recommend only using this `post_update_deployment_with_metadata` - interceptor in new development instead of the `post_update_deployment` interceptor. - When both interceptors are used, this `post_update_deployment_with_metadata` interceptor runs after the - `post_update_deployment` interceptor. The (possibly modified) response returned by - `post_update_deployment` will be passed to - `post_update_deployment_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 Config 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 Config 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 Config 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 Config 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 Config 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 Config 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 Config 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 Config 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 Config 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 Config 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 Config 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 Config 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 Config 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 Config 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 Config 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 Config 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 Config 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 Config server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class ConfigRestStub: - _session: AuthorizedSession - _host: str - _interceptor: ConfigRestInterceptor - - -class ConfigRestTransport(_BaseConfigRestTransport): - """REST backend synchronous transport for Config. - - Infrastructure Manager is a managed service that automates - the deployment and management of Google Cloud infrastructure - 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 = 'config.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[ConfigRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'config.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]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - 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. - """ - # 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 ConfigRestInterceptor() - 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': '/v1/{name=projects/*/locations/*/operations/*}:cancel', - 'body': '*', - }, - ], - 'google.longrunning.Operations.DeleteOperation': [ - { - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}', - }, - ], - 'google.longrunning.Operations.GetOperation': [ - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}', - }, - ], - 'google.longrunning.Operations.ListOperations': [ - { - 'method': 'get', - 'uri': '/v1/{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="v1") - - self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) - - # Return the client from cache. - return self._operations_client - - class _CreateDeployment(_BaseConfigRestTransport._BaseCreateDeployment, ConfigRestStub): - def __hash__(self): - return hash("ConfigRestTransport.CreateDeployment") - - @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: config.CreateDeploymentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: - r"""Call the create deployment method over HTTP. - - Args: - request (~.config.CreateDeploymentRequest): - The request 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`. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseConfigRestTransport._BaseCreateDeployment._get_http_options() - - request, metadata = self._interceptor.pre_create_deployment(request, metadata) - transcoded_request = _BaseConfigRestTransport._BaseCreateDeployment._get_transcoded_request(http_options, request) - - body = _BaseConfigRestTransport._BaseCreateDeployment._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseConfigRestTransport._BaseCreateDeployment._get_query_params_json(transcoded_request) - - 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.config_v1.ConfigClient.CreateDeployment", - extra = { - "serviceName": "google.cloud.config.v1.Config", - "rpcName": "CreateDeployment", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = ConfigRestTransport._CreateDeployment._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_deployment(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_create_deployment_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.config_v1.ConfigClient.create_deployment", - extra = { - "serviceName": "google.cloud.config.v1.Config", - "rpcName": "CreateDeployment", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _CreatePreview(_BaseConfigRestTransport._BaseCreatePreview, ConfigRestStub): - def __hash__(self): - return hash("ConfigRestTransport.CreatePreview") - - @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: config.CreatePreviewRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: - r"""Call the create preview method over HTTP. - - Args: - request (~.config.CreatePreviewRequest): - The request object. A request to create a preview. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each 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 = _BaseConfigRestTransport._BaseCreatePreview._get_http_options() - - request, metadata = self._interceptor.pre_create_preview(request, metadata) - transcoded_request = _BaseConfigRestTransport._BaseCreatePreview._get_transcoded_request(http_options, request) - - body = _BaseConfigRestTransport._BaseCreatePreview._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseConfigRestTransport._BaseCreatePreview._get_query_params_json(transcoded_request) - - 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.config_v1.ConfigClient.CreatePreview", - extra = { - "serviceName": "google.cloud.config.v1.Config", - "rpcName": "CreatePreview", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = ConfigRestTransport._CreatePreview._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_preview(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_create_preview_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.config_v1.ConfigClient.create_preview", - extra = { - "serviceName": "google.cloud.config.v1.Config", - "rpcName": "CreatePreview", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _DeleteDeployment(_BaseConfigRestTransport._BaseDeleteDeployment, ConfigRestStub): - def __hash__(self): - return hash("ConfigRestTransport.DeleteDeployment") - - @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: config.DeleteDeploymentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: - r"""Call the delete deployment method over HTTP. - - Args: - request (~.config.DeleteDeploymentRequest): - The request 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`. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseConfigRestTransport._BaseDeleteDeployment._get_http_options() - - request, metadata = self._interceptor.pre_delete_deployment(request, metadata) - transcoded_request = _BaseConfigRestTransport._BaseDeleteDeployment._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseConfigRestTransport._BaseDeleteDeployment._get_query_params_json(transcoded_request) - - 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.config_v1.ConfigClient.DeleteDeployment", - extra = { - "serviceName": "google.cloud.config.v1.Config", - "rpcName": "DeleteDeployment", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = ConfigRestTransport._DeleteDeployment._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_deployment(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_delete_deployment_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.config_v1.ConfigClient.delete_deployment", - extra = { - "serviceName": "google.cloud.config.v1.Config", - "rpcName": "DeleteDeployment", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _DeletePreview(_BaseConfigRestTransport._BaseDeletePreview, ConfigRestStub): - def __hash__(self): - return hash("ConfigRestTransport.DeletePreview") - - @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: config.DeletePreviewRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: - r"""Call the delete preview method over HTTP. - - Args: - request (~.config.DeletePreviewRequest): - The request object. A request to delete a preview. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each 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 = _BaseConfigRestTransport._BaseDeletePreview._get_http_options() - - request, metadata = self._interceptor.pre_delete_preview(request, metadata) - transcoded_request = _BaseConfigRestTransport._BaseDeletePreview._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseConfigRestTransport._BaseDeletePreview._get_query_params_json(transcoded_request) - - 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.config_v1.ConfigClient.DeletePreview", - extra = { - "serviceName": "google.cloud.config.v1.Config", - "rpcName": "DeletePreview", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = ConfigRestTransport._DeletePreview._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_preview(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_delete_preview_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.config_v1.ConfigClient.delete_preview", - extra = { - "serviceName": "google.cloud.config.v1.Config", - "rpcName": "DeletePreview", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _DeleteStatefile(_BaseConfigRestTransport._BaseDeleteStatefile, ConfigRestStub): - def __hash__(self): - return hash("ConfigRestTransport.DeleteStatefile") - - @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: config.DeleteStatefileRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ): - r"""Call the delete statefile method over HTTP. - - Args: - request (~.config.DeleteStatefileRequest): - The request object. A request to delete a state file - passed to a 'DeleteStatefile' call. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, 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 = _BaseConfigRestTransport._BaseDeleteStatefile._get_http_options() - - request, metadata = self._interceptor.pre_delete_statefile(request, metadata) - transcoded_request = _BaseConfigRestTransport._BaseDeleteStatefile._get_transcoded_request(http_options, request) - - body = _BaseConfigRestTransport._BaseDeleteStatefile._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseConfigRestTransport._BaseDeleteStatefile._get_query_params_json(transcoded_request) - - 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.config_v1.ConfigClient.DeleteStatefile", - extra = { - "serviceName": "google.cloud.config.v1.Config", - "rpcName": "DeleteStatefile", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = ConfigRestTransport._DeleteStatefile._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 _ExportDeploymentStatefile(_BaseConfigRestTransport._BaseExportDeploymentStatefile, ConfigRestStub): - def __hash__(self): - return hash("ConfigRestTransport.ExportDeploymentStatefile") - - @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: config.ExportDeploymentStatefileRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> config.Statefile: - r"""Call the export deployment - statefile method over HTTP. - - Args: - request (~.config.ExportDeploymentStatefileRequest): - The request object. A request to export a state file - passed to a 'ExportDeploymentStatefile' - call. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.config.Statefile: - Contains info about a Terraform state - file - - """ - - http_options = _BaseConfigRestTransport._BaseExportDeploymentStatefile._get_http_options() - - request, metadata = self._interceptor.pre_export_deployment_statefile(request, metadata) - transcoded_request = _BaseConfigRestTransport._BaseExportDeploymentStatefile._get_transcoded_request(http_options, request) - - body = _BaseConfigRestTransport._BaseExportDeploymentStatefile._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseConfigRestTransport._BaseExportDeploymentStatefile._get_query_params_json(transcoded_request) - - 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.config_v1.ConfigClient.ExportDeploymentStatefile", - extra = { - "serviceName": "google.cloud.config.v1.Config", - "rpcName": "ExportDeploymentStatefile", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = ConfigRestTransport._ExportDeploymentStatefile._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 = config.Statefile() - pb_resp = config.Statefile.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_export_deployment_statefile(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_export_deployment_statefile_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = config.Statefile.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.config_v1.ConfigClient.export_deployment_statefile", - extra = { - "serviceName": "google.cloud.config.v1.Config", - "rpcName": "ExportDeploymentStatefile", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _ExportLockInfo(_BaseConfigRestTransport._BaseExportLockInfo, ConfigRestStub): - def __hash__(self): - return hash("ConfigRestTransport.ExportLockInfo") - - @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: config.ExportLockInfoRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> config.LockInfo: - r"""Call the export lock info method over HTTP. - - Args: - request (~.config.ExportLockInfoRequest): - The request object. A request to get a state file lock - info passed to a 'ExportLockInfo' call. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.config.LockInfo: - Details about the lock which locked - the deployment. - - """ - - http_options = _BaseConfigRestTransport._BaseExportLockInfo._get_http_options() - - request, metadata = self._interceptor.pre_export_lock_info(request, metadata) - transcoded_request = _BaseConfigRestTransport._BaseExportLockInfo._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseConfigRestTransport._BaseExportLockInfo._get_query_params_json(transcoded_request) - - 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.config_v1.ConfigClient.ExportLockInfo", - extra = { - "serviceName": "google.cloud.config.v1.Config", - "rpcName": "ExportLockInfo", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = ConfigRestTransport._ExportLockInfo._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 = config.LockInfo() - pb_resp = config.LockInfo.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_export_lock_info(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_export_lock_info_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = config.LockInfo.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.config_v1.ConfigClient.export_lock_info", - extra = { - "serviceName": "google.cloud.config.v1.Config", - "rpcName": "ExportLockInfo", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _ExportPreviewResult(_BaseConfigRestTransport._BaseExportPreviewResult, ConfigRestStub): - def __hash__(self): - return hash("ConfigRestTransport.ExportPreviewResult") - - @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: config.ExportPreviewResultRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> config.ExportPreviewResultResponse: - r"""Call the export preview result method over HTTP. - - Args: - request (~.config.ExportPreviewResultRequest): - The request object. A request to export preview results. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.config.ExportPreviewResultResponse: - A response to ``ExportPreviewResult`` call. Contains - preview results. - - """ - - http_options = _BaseConfigRestTransport._BaseExportPreviewResult._get_http_options() - - request, metadata = self._interceptor.pre_export_preview_result(request, metadata) - transcoded_request = _BaseConfigRestTransport._BaseExportPreviewResult._get_transcoded_request(http_options, request) - - body = _BaseConfigRestTransport._BaseExportPreviewResult._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseConfigRestTransport._BaseExportPreviewResult._get_query_params_json(transcoded_request) - - 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.config_v1.ConfigClient.ExportPreviewResult", - extra = { - "serviceName": "google.cloud.config.v1.Config", - "rpcName": "ExportPreviewResult", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = ConfigRestTransport._ExportPreviewResult._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 = config.ExportPreviewResultResponse() - pb_resp = config.ExportPreviewResultResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_export_preview_result(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_export_preview_result_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = config.ExportPreviewResultResponse.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.config_v1.ConfigClient.export_preview_result", - extra = { - "serviceName": "google.cloud.config.v1.Config", - "rpcName": "ExportPreviewResult", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _ExportRevisionStatefile(_BaseConfigRestTransport._BaseExportRevisionStatefile, ConfigRestStub): - def __hash__(self): - return hash("ConfigRestTransport.ExportRevisionStatefile") - - @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: config.ExportRevisionStatefileRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> config.Statefile: - r"""Call the export revision statefile method over HTTP. - - Args: - request (~.config.ExportRevisionStatefileRequest): - The request object. A request to export a state file - passed to a 'ExportRevisionStatefile' - call. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.config.Statefile: - Contains info about a Terraform state - file - - """ - - http_options = _BaseConfigRestTransport._BaseExportRevisionStatefile._get_http_options() - - request, metadata = self._interceptor.pre_export_revision_statefile(request, metadata) - transcoded_request = _BaseConfigRestTransport._BaseExportRevisionStatefile._get_transcoded_request(http_options, request) - - body = _BaseConfigRestTransport._BaseExportRevisionStatefile._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseConfigRestTransport._BaseExportRevisionStatefile._get_query_params_json(transcoded_request) - - 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.config_v1.ConfigClient.ExportRevisionStatefile", - extra = { - "serviceName": "google.cloud.config.v1.Config", - "rpcName": "ExportRevisionStatefile", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = ConfigRestTransport._ExportRevisionStatefile._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 = config.Statefile() - pb_resp = config.Statefile.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_export_revision_statefile(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_export_revision_statefile_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = config.Statefile.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.config_v1.ConfigClient.export_revision_statefile", - extra = { - "serviceName": "google.cloud.config.v1.Config", - "rpcName": "ExportRevisionStatefile", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _GetDeployment(_BaseConfigRestTransport._BaseGetDeployment, ConfigRestStub): - def __hash__(self): - return hash("ConfigRestTransport.GetDeployment") - - @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: config.GetDeploymentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> config.Deployment: - r"""Call the get deployment method over HTTP. - - Args: - request (~.config.GetDeploymentRequest): - The request 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`. - - Returns: - ~.config.Deployment: - A Deployment is a group of resources - and configs managed and provisioned by - Infra Manager. - - """ - - http_options = _BaseConfigRestTransport._BaseGetDeployment._get_http_options() - - request, metadata = self._interceptor.pre_get_deployment(request, metadata) - transcoded_request = _BaseConfigRestTransport._BaseGetDeployment._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseConfigRestTransport._BaseGetDeployment._get_query_params_json(transcoded_request) - - 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.config_v1.ConfigClient.GetDeployment", - extra = { - "serviceName": "google.cloud.config.v1.Config", - "rpcName": "GetDeployment", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = ConfigRestTransport._GetDeployment._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 = config.Deployment() - pb_resp = config.Deployment.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_get_deployment(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_deployment_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = config.Deployment.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.config_v1.ConfigClient.get_deployment", - extra = { - "serviceName": "google.cloud.config.v1.Config", - "rpcName": "GetDeployment", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _GetPreview(_BaseConfigRestTransport._BaseGetPreview, ConfigRestStub): - def __hash__(self): - return hash("ConfigRestTransport.GetPreview") - - @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: config.GetPreviewRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> config.Preview: - r"""Call the get preview method over HTTP. - - Args: - request (~.config.GetPreviewRequest): - The request object. A request to get details about a - preview. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.config.Preview: - A preview represents a set of actions - Infra Manager would perform to move the - resources towards the desired state as - specified in the configuration. - - """ - - http_options = _BaseConfigRestTransport._BaseGetPreview._get_http_options() - - request, metadata = self._interceptor.pre_get_preview(request, metadata) - transcoded_request = _BaseConfigRestTransport._BaseGetPreview._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseConfigRestTransport._BaseGetPreview._get_query_params_json(transcoded_request) - - 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.config_v1.ConfigClient.GetPreview", - extra = { - "serviceName": "google.cloud.config.v1.Config", - "rpcName": "GetPreview", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = ConfigRestTransport._GetPreview._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 = config.Preview() - pb_resp = config.Preview.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_get_preview(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_preview_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = config.Preview.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.config_v1.ConfigClient.get_preview", - extra = { - "serviceName": "google.cloud.config.v1.Config", - "rpcName": "GetPreview", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _GetResource(_BaseConfigRestTransport._BaseGetResource, ConfigRestStub): - def __hash__(self): - return hash("ConfigRestTransport.GetResource") - - @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: config.GetResourceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> config.Resource: - r"""Call the get resource method over HTTP. - - Args: - request (~.config.GetResourceRequest): - The request object. A request to get a Resource from a - 'GetResource' call. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.config.Resource: - Resource represents a Google Cloud - Platform resource actuated by IM. - Resources are child resources of - Revisions. - - """ - - http_options = _BaseConfigRestTransport._BaseGetResource._get_http_options() - - request, metadata = self._interceptor.pre_get_resource(request, metadata) - transcoded_request = _BaseConfigRestTransport._BaseGetResource._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseConfigRestTransport._BaseGetResource._get_query_params_json(transcoded_request) - - 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.config_v1.ConfigClient.GetResource", - extra = { - "serviceName": "google.cloud.config.v1.Config", - "rpcName": "GetResource", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = ConfigRestTransport._GetResource._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 = config.Resource() - pb_resp = config.Resource.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_get_resource(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_resource_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = config.Resource.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.config_v1.ConfigClient.get_resource", - extra = { - "serviceName": "google.cloud.config.v1.Config", - "rpcName": "GetResource", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _GetResourceChange(_BaseConfigRestTransport._BaseGetResourceChange, ConfigRestStub): - def __hash__(self): - return hash("ConfigRestTransport.GetResourceChange") - - @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: config.GetResourceChangeRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> config.ResourceChange: - r"""Call the get resource change method over HTTP. - - Args: - request (~.config.GetResourceChangeRequest): - The request object. The request message for the - GetResourceChange 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: - ~.config.ResourceChange: - A resource change represents a change - to a resource in the state file. - - """ - - http_options = _BaseConfigRestTransport._BaseGetResourceChange._get_http_options() - - request, metadata = self._interceptor.pre_get_resource_change(request, metadata) - transcoded_request = _BaseConfigRestTransport._BaseGetResourceChange._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseConfigRestTransport._BaseGetResourceChange._get_query_params_json(transcoded_request) - - 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.config_v1.ConfigClient.GetResourceChange", - extra = { - "serviceName": "google.cloud.config.v1.Config", - "rpcName": "GetResourceChange", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = ConfigRestTransport._GetResourceChange._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 = config.ResourceChange() - pb_resp = config.ResourceChange.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_get_resource_change(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_resource_change_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = config.ResourceChange.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.config_v1.ConfigClient.get_resource_change", - extra = { - "serviceName": "google.cloud.config.v1.Config", - "rpcName": "GetResourceChange", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _GetResourceDrift(_BaseConfigRestTransport._BaseGetResourceDrift, ConfigRestStub): - def __hash__(self): - return hash("ConfigRestTransport.GetResourceDrift") - - @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: config.GetResourceDriftRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> config.ResourceDrift: - r"""Call the get resource drift method over HTTP. - - Args: - request (~.config.GetResourceDriftRequest): - The request object. The request message for the - GetResourceDrift 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: - ~.config.ResourceDrift: - A resource drift represents a drift - to a resource in the state file. - - """ - - http_options = _BaseConfigRestTransport._BaseGetResourceDrift._get_http_options() - - request, metadata = self._interceptor.pre_get_resource_drift(request, metadata) - transcoded_request = _BaseConfigRestTransport._BaseGetResourceDrift._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseConfigRestTransport._BaseGetResourceDrift._get_query_params_json(transcoded_request) - - 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.config_v1.ConfigClient.GetResourceDrift", - extra = { - "serviceName": "google.cloud.config.v1.Config", - "rpcName": "GetResourceDrift", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = ConfigRestTransport._GetResourceDrift._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 = config.ResourceDrift() - pb_resp = config.ResourceDrift.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_get_resource_drift(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_resource_drift_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = config.ResourceDrift.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.config_v1.ConfigClient.get_resource_drift", - extra = { - "serviceName": "google.cloud.config.v1.Config", - "rpcName": "GetResourceDrift", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _GetRevision(_BaseConfigRestTransport._BaseGetRevision, ConfigRestStub): - def __hash__(self): - return hash("ConfigRestTransport.GetRevision") - - @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: config.GetRevisionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> config.Revision: - r"""Call the get revision method over HTTP. - - Args: - request (~.config.GetRevisionRequest): - The request object. A request to get a Revision from a - 'GetRevision' call. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.config.Revision: - A child resource of a Deployment - generated by a 'CreateDeployment' or - 'UpdateDeployment' call. Each Revision - contains metadata pertaining to a - snapshot of a particular Deployment. - - """ - - http_options = _BaseConfigRestTransport._BaseGetRevision._get_http_options() - - request, metadata = self._interceptor.pre_get_revision(request, metadata) - transcoded_request = _BaseConfigRestTransport._BaseGetRevision._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseConfigRestTransport._BaseGetRevision._get_query_params_json(transcoded_request) - - 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.config_v1.ConfigClient.GetRevision", - extra = { - "serviceName": "google.cloud.config.v1.Config", - "rpcName": "GetRevision", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = ConfigRestTransport._GetRevision._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 = config.Revision() - pb_resp = config.Revision.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_get_revision(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_revision_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = config.Revision.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.config_v1.ConfigClient.get_revision", - extra = { - "serviceName": "google.cloud.config.v1.Config", - "rpcName": "GetRevision", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _GetTerraformVersion(_BaseConfigRestTransport._BaseGetTerraformVersion, ConfigRestStub): - def __hash__(self): - return hash("ConfigRestTransport.GetTerraformVersion") - - @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: config.GetTerraformVersionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> config.TerraformVersion: - r"""Call the get terraform version method over HTTP. - - Args: - request (~.config.GetTerraformVersionRequest): - The request object. The request message for the - GetTerraformVersion 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: - ~.config.TerraformVersion: - A TerraformVersion represents the - support state the corresponding - Terraform version. - - """ - - http_options = _BaseConfigRestTransport._BaseGetTerraformVersion._get_http_options() - - request, metadata = self._interceptor.pre_get_terraform_version(request, metadata) - transcoded_request = _BaseConfigRestTransport._BaseGetTerraformVersion._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseConfigRestTransport._BaseGetTerraformVersion._get_query_params_json(transcoded_request) - - 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.config_v1.ConfigClient.GetTerraformVersion", - extra = { - "serviceName": "google.cloud.config.v1.Config", - "rpcName": "GetTerraformVersion", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = ConfigRestTransport._GetTerraformVersion._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 = config.TerraformVersion() - pb_resp = config.TerraformVersion.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_get_terraform_version(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_terraform_version_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = config.TerraformVersion.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.config_v1.ConfigClient.get_terraform_version", - extra = { - "serviceName": "google.cloud.config.v1.Config", - "rpcName": "GetTerraformVersion", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _ImportStatefile(_BaseConfigRestTransport._BaseImportStatefile, ConfigRestStub): - def __hash__(self): - return hash("ConfigRestTransport.ImportStatefile") - - @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: config.ImportStatefileRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> config.Statefile: - r"""Call the import statefile method over HTTP. - - Args: - request (~.config.ImportStatefileRequest): - The request object. A request to import a state file - passed to a 'ImportStatefile' call. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.config.Statefile: - Contains info about a Terraform state - file - - """ - - http_options = _BaseConfigRestTransport._BaseImportStatefile._get_http_options() - - request, metadata = self._interceptor.pre_import_statefile(request, metadata) - transcoded_request = _BaseConfigRestTransport._BaseImportStatefile._get_transcoded_request(http_options, request) - - body = _BaseConfigRestTransport._BaseImportStatefile._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseConfigRestTransport._BaseImportStatefile._get_query_params_json(transcoded_request) - - 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.config_v1.ConfigClient.ImportStatefile", - extra = { - "serviceName": "google.cloud.config.v1.Config", - "rpcName": "ImportStatefile", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = ConfigRestTransport._ImportStatefile._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 = config.Statefile() - pb_resp = config.Statefile.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_import_statefile(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_import_statefile_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = config.Statefile.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.config_v1.ConfigClient.import_statefile", - extra = { - "serviceName": "google.cloud.config.v1.Config", - "rpcName": "ImportStatefile", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _ListDeployments(_BaseConfigRestTransport._BaseListDeployments, ConfigRestStub): - def __hash__(self): - return hash("ConfigRestTransport.ListDeployments") - - @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: config.ListDeploymentsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> config.ListDeploymentsResponse: - r"""Call the list deployments method over HTTP. - - Args: - request (~.config.ListDeploymentsRequest): - The request 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`. - - Returns: - ~.config.ListDeploymentsResponse: - - """ - - http_options = _BaseConfigRestTransport._BaseListDeployments._get_http_options() - - request, metadata = self._interceptor.pre_list_deployments(request, metadata) - transcoded_request = _BaseConfigRestTransport._BaseListDeployments._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseConfigRestTransport._BaseListDeployments._get_query_params_json(transcoded_request) - - 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.config_v1.ConfigClient.ListDeployments", - extra = { - "serviceName": "google.cloud.config.v1.Config", - "rpcName": "ListDeployments", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = ConfigRestTransport._ListDeployments._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 = config.ListDeploymentsResponse() - pb_resp = config.ListDeploymentsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_list_deployments(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_deployments_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = config.ListDeploymentsResponse.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.config_v1.ConfigClient.list_deployments", - extra = { - "serviceName": "google.cloud.config.v1.Config", - "rpcName": "ListDeployments", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _ListPreviews(_BaseConfigRestTransport._BaseListPreviews, ConfigRestStub): - def __hash__(self): - return hash("ConfigRestTransport.ListPreviews") - - @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: config.ListPreviewsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> config.ListPreviewsResponse: - r"""Call the list previews method over HTTP. - - Args: - request (~.config.ListPreviewsRequest): - The request object. A request to list all previews for a - given project and location. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.config.ListPreviewsResponse: - A response to a ``ListPreviews`` call. Contains a list - of Previews. - - """ - - http_options = _BaseConfigRestTransport._BaseListPreviews._get_http_options() - - request, metadata = self._interceptor.pre_list_previews(request, metadata) - transcoded_request = _BaseConfigRestTransport._BaseListPreviews._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseConfigRestTransport._BaseListPreviews._get_query_params_json(transcoded_request) - - 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.config_v1.ConfigClient.ListPreviews", - extra = { - "serviceName": "google.cloud.config.v1.Config", - "rpcName": "ListPreviews", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = ConfigRestTransport._ListPreviews._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 = config.ListPreviewsResponse() - pb_resp = config.ListPreviewsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_list_previews(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_previews_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = config.ListPreviewsResponse.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.config_v1.ConfigClient.list_previews", - extra = { - "serviceName": "google.cloud.config.v1.Config", - "rpcName": "ListPreviews", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _ListResourceChanges(_BaseConfigRestTransport._BaseListResourceChanges, ConfigRestStub): - def __hash__(self): - return hash("ConfigRestTransport.ListResourceChanges") - - @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: config.ListResourceChangesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> config.ListResourceChangesResponse: - r"""Call the list resource changes method over HTTP. - - Args: - request (~.config.ListResourceChangesRequest): - The request object. The request message for the - ListResourceChanges 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: - ~.config.ListResourceChangesResponse: - A response to a 'ListResourceChanges' - call. Contains a list of - ResourceChanges. - - """ - - http_options = _BaseConfigRestTransport._BaseListResourceChanges._get_http_options() - - request, metadata = self._interceptor.pre_list_resource_changes(request, metadata) - transcoded_request = _BaseConfigRestTransport._BaseListResourceChanges._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseConfigRestTransport._BaseListResourceChanges._get_query_params_json(transcoded_request) - - 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.config_v1.ConfigClient.ListResourceChanges", - extra = { - "serviceName": "google.cloud.config.v1.Config", - "rpcName": "ListResourceChanges", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = ConfigRestTransport._ListResourceChanges._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 = config.ListResourceChangesResponse() - pb_resp = config.ListResourceChangesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_list_resource_changes(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_resource_changes_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = config.ListResourceChangesResponse.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.config_v1.ConfigClient.list_resource_changes", - extra = { - "serviceName": "google.cloud.config.v1.Config", - "rpcName": "ListResourceChanges", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _ListResourceDrifts(_BaseConfigRestTransport._BaseListResourceDrifts, ConfigRestStub): - def __hash__(self): - return hash("ConfigRestTransport.ListResourceDrifts") - - @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: config.ListResourceDriftsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> config.ListResourceDriftsResponse: - r"""Call the list resource drifts method over HTTP. - - Args: - request (~.config.ListResourceDriftsRequest): - The request object. The request message for the - ListResourceDrifts 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: - ~.config.ListResourceDriftsResponse: - A response to a 'ListResourceDrifts' - call. Contains a list of ResourceDrifts. - - """ - - http_options = _BaseConfigRestTransport._BaseListResourceDrifts._get_http_options() - - request, metadata = self._interceptor.pre_list_resource_drifts(request, metadata) - transcoded_request = _BaseConfigRestTransport._BaseListResourceDrifts._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseConfigRestTransport._BaseListResourceDrifts._get_query_params_json(transcoded_request) - - 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.config_v1.ConfigClient.ListResourceDrifts", - extra = { - "serviceName": "google.cloud.config.v1.Config", - "rpcName": "ListResourceDrifts", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = ConfigRestTransport._ListResourceDrifts._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 = config.ListResourceDriftsResponse() - pb_resp = config.ListResourceDriftsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_list_resource_drifts(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_resource_drifts_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = config.ListResourceDriftsResponse.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.config_v1.ConfigClient.list_resource_drifts", - extra = { - "serviceName": "google.cloud.config.v1.Config", - "rpcName": "ListResourceDrifts", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _ListResources(_BaseConfigRestTransport._BaseListResources, ConfigRestStub): - def __hash__(self): - return hash("ConfigRestTransport.ListResources") - - @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: config.ListResourcesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> config.ListResourcesResponse: - r"""Call the list resources method over HTTP. - - Args: - request (~.config.ListResourcesRequest): - The request object. A request to list Resources passed to - a 'ListResources' call. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.config.ListResourcesResponse: - A response to a 'ListResources' call. - Contains a list of Resources. - - """ - - http_options = _BaseConfigRestTransport._BaseListResources._get_http_options() - - request, metadata = self._interceptor.pre_list_resources(request, metadata) - transcoded_request = _BaseConfigRestTransport._BaseListResources._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseConfigRestTransport._BaseListResources._get_query_params_json(transcoded_request) - - 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.config_v1.ConfigClient.ListResources", - extra = { - "serviceName": "google.cloud.config.v1.Config", - "rpcName": "ListResources", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = ConfigRestTransport._ListResources._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 = config.ListResourcesResponse() - pb_resp = config.ListResourcesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_list_resources(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_resources_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = config.ListResourcesResponse.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.config_v1.ConfigClient.list_resources", - extra = { - "serviceName": "google.cloud.config.v1.Config", - "rpcName": "ListResources", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _ListRevisions(_BaseConfigRestTransport._BaseListRevisions, ConfigRestStub): - def __hash__(self): - return hash("ConfigRestTransport.ListRevisions") - - @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: config.ListRevisionsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> config.ListRevisionsResponse: - r"""Call the list revisions method over HTTP. - - Args: - request (~.config.ListRevisionsRequest): - The request object. A request to list Revisions passed to - a 'ListRevisions' call. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.config.ListRevisionsResponse: - A response to a 'ListRevisions' call. - Contains a list of Revisions. - - """ - - http_options = _BaseConfigRestTransport._BaseListRevisions._get_http_options() - - request, metadata = self._interceptor.pre_list_revisions(request, metadata) - transcoded_request = _BaseConfigRestTransport._BaseListRevisions._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseConfigRestTransport._BaseListRevisions._get_query_params_json(transcoded_request) - - 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.config_v1.ConfigClient.ListRevisions", - extra = { - "serviceName": "google.cloud.config.v1.Config", - "rpcName": "ListRevisions", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = ConfigRestTransport._ListRevisions._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 = config.ListRevisionsResponse() - pb_resp = config.ListRevisionsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_list_revisions(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_revisions_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = config.ListRevisionsResponse.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.config_v1.ConfigClient.list_revisions", - extra = { - "serviceName": "google.cloud.config.v1.Config", - "rpcName": "ListRevisions", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _ListTerraformVersions(_BaseConfigRestTransport._BaseListTerraformVersions, ConfigRestStub): - def __hash__(self): - return hash("ConfigRestTransport.ListTerraformVersions") - - @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: config.ListTerraformVersionsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> config.ListTerraformVersionsResponse: - r"""Call the list terraform versions method over HTTP. - - Args: - request (~.config.ListTerraformVersionsRequest): - The request object. The request message for the - ListTerraformVersions 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: - ~.config.ListTerraformVersionsResponse: - The response message for the ``ListTerraformVersions`` - method. - - """ - - http_options = _BaseConfigRestTransport._BaseListTerraformVersions._get_http_options() - - request, metadata = self._interceptor.pre_list_terraform_versions(request, metadata) - transcoded_request = _BaseConfigRestTransport._BaseListTerraformVersions._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseConfigRestTransport._BaseListTerraformVersions._get_query_params_json(transcoded_request) - - 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.config_v1.ConfigClient.ListTerraformVersions", - extra = { - "serviceName": "google.cloud.config.v1.Config", - "rpcName": "ListTerraformVersions", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = ConfigRestTransport._ListTerraformVersions._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 = config.ListTerraformVersionsResponse() - pb_resp = config.ListTerraformVersionsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_list_terraform_versions(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_terraform_versions_with_metadata(resp, response_metadata) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = config.ListTerraformVersionsResponse.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.config_v1.ConfigClient.list_terraform_versions", - extra = { - "serviceName": "google.cloud.config.v1.Config", - "rpcName": "ListTerraformVersions", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _LockDeployment(_BaseConfigRestTransport._BaseLockDeployment, ConfigRestStub): - def __hash__(self): - return hash("ConfigRestTransport.LockDeployment") - - @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: config.LockDeploymentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: - r"""Call the lock deployment method over HTTP. - - Args: - request (~.config.LockDeploymentRequest): - The request object. A request to lock a deployment passed - to a 'LockDeployment' call. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each 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 = _BaseConfigRestTransport._BaseLockDeployment._get_http_options() - - request, metadata = self._interceptor.pre_lock_deployment(request, metadata) - transcoded_request = _BaseConfigRestTransport._BaseLockDeployment._get_transcoded_request(http_options, request) - - body = _BaseConfigRestTransport._BaseLockDeployment._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseConfigRestTransport._BaseLockDeployment._get_query_params_json(transcoded_request) - - 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.config_v1.ConfigClient.LockDeployment", - extra = { - "serviceName": "google.cloud.config.v1.Config", - "rpcName": "LockDeployment", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = ConfigRestTransport._LockDeployment._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_lock_deployment(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_lock_deployment_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.config_v1.ConfigClient.lock_deployment", - extra = { - "serviceName": "google.cloud.config.v1.Config", - "rpcName": "LockDeployment", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _UnlockDeployment(_BaseConfigRestTransport._BaseUnlockDeployment, ConfigRestStub): - def __hash__(self): - return hash("ConfigRestTransport.UnlockDeployment") - - @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: config.UnlockDeploymentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: - r"""Call the unlock deployment method over HTTP. - - Args: - request (~.config.UnlockDeploymentRequest): - The request object. A request to unlock a state file - passed to a 'UnlockDeployment' call. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each 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 = _BaseConfigRestTransport._BaseUnlockDeployment._get_http_options() - - request, metadata = self._interceptor.pre_unlock_deployment(request, metadata) - transcoded_request = _BaseConfigRestTransport._BaseUnlockDeployment._get_transcoded_request(http_options, request) - - body = _BaseConfigRestTransport._BaseUnlockDeployment._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseConfigRestTransport._BaseUnlockDeployment._get_query_params_json(transcoded_request) - - 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.config_v1.ConfigClient.UnlockDeployment", - extra = { - "serviceName": "google.cloud.config.v1.Config", - "rpcName": "UnlockDeployment", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = ConfigRestTransport._UnlockDeployment._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_unlock_deployment(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_unlock_deployment_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.config_v1.ConfigClient.unlock_deployment", - extra = { - "serviceName": "google.cloud.config.v1.Config", - "rpcName": "UnlockDeployment", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _UpdateDeployment(_BaseConfigRestTransport._BaseUpdateDeployment, ConfigRestStub): - def __hash__(self): - return hash("ConfigRestTransport.UpdateDeployment") - - @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: config.UpdateDeploymentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: - r"""Call the update deployment method over HTTP. - - Args: - request (~.config.UpdateDeploymentRequest): - The request 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`. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseConfigRestTransport._BaseUpdateDeployment._get_http_options() - - request, metadata = self._interceptor.pre_update_deployment(request, metadata) - transcoded_request = _BaseConfigRestTransport._BaseUpdateDeployment._get_transcoded_request(http_options, request) - - body = _BaseConfigRestTransport._BaseUpdateDeployment._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseConfigRestTransport._BaseUpdateDeployment._get_query_params_json(transcoded_request) - - 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.config_v1.ConfigClient.UpdateDeployment", - extra = { - "serviceName": "google.cloud.config.v1.Config", - "rpcName": "UpdateDeployment", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = ConfigRestTransport._UpdateDeployment._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_deployment(resp) - response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_update_deployment_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.config_v1.ConfigClient.update_deployment", - extra = { - "serviceName": "google.cloud.config.v1.Config", - "rpcName": "UpdateDeployment", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - @property - def create_deployment(self) -> Callable[ - [config.CreateDeploymentRequest], - 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._CreateDeployment(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_preview(self) -> Callable[ - [config.CreatePreviewRequest], - 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._CreatePreview(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_deployment(self) -> Callable[ - [config.DeleteDeploymentRequest], - 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._DeleteDeployment(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_preview(self) -> Callable[ - [config.DeletePreviewRequest], - 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._DeletePreview(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_statefile(self) -> Callable[ - [config.DeleteStatefileRequest], - 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._DeleteStatefile(self._session, self._host, self._interceptor) # type: ignore - - @property - def export_deployment_statefile(self) -> Callable[ - [config.ExportDeploymentStatefileRequest], - config.Statefile]: - # 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._ExportDeploymentStatefile(self._session, self._host, self._interceptor) # type: ignore - - @property - def export_lock_info(self) -> Callable[ - [config.ExportLockInfoRequest], - config.LockInfo]: - # 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._ExportLockInfo(self._session, self._host, self._interceptor) # type: ignore - - @property - def export_preview_result(self) -> Callable[ - [config.ExportPreviewResultRequest], - config.ExportPreviewResultResponse]: - # 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._ExportPreviewResult(self._session, self._host, self._interceptor) # type: ignore - - @property - def export_revision_statefile(self) -> Callable[ - [config.ExportRevisionStatefileRequest], - config.Statefile]: - # 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._ExportRevisionStatefile(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_deployment(self) -> Callable[ - [config.GetDeploymentRequest], - config.Deployment]: - # 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._GetDeployment(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_preview(self) -> Callable[ - [config.GetPreviewRequest], - config.Preview]: - # 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._GetPreview(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_resource(self) -> Callable[ - [config.GetResourceRequest], - config.Resource]: - # 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._GetResource(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_resource_change(self) -> Callable[ - [config.GetResourceChangeRequest], - config.ResourceChange]: - # 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._GetResourceChange(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_resource_drift(self) -> Callable[ - [config.GetResourceDriftRequest], - config.ResourceDrift]: - # 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._GetResourceDrift(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_revision(self) -> Callable[ - [config.GetRevisionRequest], - config.Revision]: - # 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._GetRevision(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_terraform_version(self) -> Callable[ - [config.GetTerraformVersionRequest], - config.TerraformVersion]: - # 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._GetTerraformVersion(self._session, self._host, self._interceptor) # type: ignore - - @property - def import_statefile(self) -> Callable[ - [config.ImportStatefileRequest], - config.Statefile]: - # 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._ImportStatefile(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_deployments(self) -> Callable[ - [config.ListDeploymentsRequest], - config.ListDeploymentsResponse]: - # 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._ListDeployments(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_previews(self) -> Callable[ - [config.ListPreviewsRequest], - config.ListPreviewsResponse]: - # 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._ListPreviews(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_resource_changes(self) -> Callable[ - [config.ListResourceChangesRequest], - config.ListResourceChangesResponse]: - # 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._ListResourceChanges(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_resource_drifts(self) -> Callable[ - [config.ListResourceDriftsRequest], - config.ListResourceDriftsResponse]: - # 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._ListResourceDrifts(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_resources(self) -> Callable[ - [config.ListResourcesRequest], - config.ListResourcesResponse]: - # 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._ListResources(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_revisions(self) -> Callable[ - [config.ListRevisionsRequest], - config.ListRevisionsResponse]: - # 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._ListRevisions(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_terraform_versions(self) -> Callable[ - [config.ListTerraformVersionsRequest], - config.ListTerraformVersionsResponse]: - # 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._ListTerraformVersions(self._session, self._host, self._interceptor) # type: ignore - - @property - def lock_deployment(self) -> Callable[ - [config.LockDeploymentRequest], - 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._LockDeployment(self._session, self._host, self._interceptor) # type: ignore - - @property - def unlock_deployment(self) -> Callable[ - [config.UnlockDeploymentRequest], - 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._UnlockDeployment(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_deployment(self) -> Callable[ - [config.UpdateDeploymentRequest], - 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._UpdateDeployment(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(_BaseConfigRestTransport._BaseGetLocation, ConfigRestStub): - def __hash__(self): - return hash("ConfigRestTransport.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 = _BaseConfigRestTransport._BaseGetLocation._get_http_options() - - request, metadata = self._interceptor.pre_get_location(request, metadata) - transcoded_request = _BaseConfigRestTransport._BaseGetLocation._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseConfigRestTransport._BaseGetLocation._get_query_params_json(transcoded_request) - - 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.config_v1.ConfigClient.GetLocation", - extra = { - "serviceName": "google.cloud.config.v1.Config", - "rpcName": "GetLocation", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = ConfigRestTransport._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.config_v1.ConfigAsyncClient.GetLocation", - extra = { - "serviceName": "google.cloud.config.v1.Config", - "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(_BaseConfigRestTransport._BaseListLocations, ConfigRestStub): - def __hash__(self): - return hash("ConfigRestTransport.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 = _BaseConfigRestTransport._BaseListLocations._get_http_options() - - request, metadata = self._interceptor.pre_list_locations(request, metadata) - transcoded_request = _BaseConfigRestTransport._BaseListLocations._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseConfigRestTransport._BaseListLocations._get_query_params_json(transcoded_request) - - 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.config_v1.ConfigClient.ListLocations", - extra = { - "serviceName": "google.cloud.config.v1.Config", - "rpcName": "ListLocations", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = ConfigRestTransport._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.config_v1.ConfigAsyncClient.ListLocations", - extra = { - "serviceName": "google.cloud.config.v1.Config", - "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(_BaseConfigRestTransport._BaseGetIamPolicy, ConfigRestStub): - def __hash__(self): - return hash("ConfigRestTransport.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 = _BaseConfigRestTransport._BaseGetIamPolicy._get_http_options() - - request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) - transcoded_request = _BaseConfigRestTransport._BaseGetIamPolicy._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseConfigRestTransport._BaseGetIamPolicy._get_query_params_json(transcoded_request) - - 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.config_v1.ConfigClient.GetIamPolicy", - extra = { - "serviceName": "google.cloud.config.v1.Config", - "rpcName": "GetIamPolicy", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = ConfigRestTransport._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.config_v1.ConfigAsyncClient.GetIamPolicy", - extra = { - "serviceName": "google.cloud.config.v1.Config", - "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(_BaseConfigRestTransport._BaseSetIamPolicy, ConfigRestStub): - def __hash__(self): - return hash("ConfigRestTransport.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 = _BaseConfigRestTransport._BaseSetIamPolicy._get_http_options() - - request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) - transcoded_request = _BaseConfigRestTransport._BaseSetIamPolicy._get_transcoded_request(http_options, request) - - body = _BaseConfigRestTransport._BaseSetIamPolicy._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseConfigRestTransport._BaseSetIamPolicy._get_query_params_json(transcoded_request) - - 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.config_v1.ConfigClient.SetIamPolicy", - extra = { - "serviceName": "google.cloud.config.v1.Config", - "rpcName": "SetIamPolicy", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = ConfigRestTransport._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.config_v1.ConfigAsyncClient.SetIamPolicy", - extra = { - "serviceName": "google.cloud.config.v1.Config", - "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(_BaseConfigRestTransport._BaseTestIamPermissions, ConfigRestStub): - def __hash__(self): - return hash("ConfigRestTransport.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 = _BaseConfigRestTransport._BaseTestIamPermissions._get_http_options() - - request, metadata = self._interceptor.pre_test_iam_permissions(request, metadata) - transcoded_request = _BaseConfigRestTransport._BaseTestIamPermissions._get_transcoded_request(http_options, request) - - body = _BaseConfigRestTransport._BaseTestIamPermissions._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseConfigRestTransport._BaseTestIamPermissions._get_query_params_json(transcoded_request) - - 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.config_v1.ConfigClient.TestIamPermissions", - extra = { - "serviceName": "google.cloud.config.v1.Config", - "rpcName": "TestIamPermissions", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = ConfigRestTransport._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.config_v1.ConfigAsyncClient.TestIamPermissions", - extra = { - "serviceName": "google.cloud.config.v1.Config", - "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(_BaseConfigRestTransport._BaseCancelOperation, ConfigRestStub): - def __hash__(self): - return hash("ConfigRestTransport.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 = _BaseConfigRestTransport._BaseCancelOperation._get_http_options() - - request, metadata = self._interceptor.pre_cancel_operation(request, metadata) - transcoded_request = _BaseConfigRestTransport._BaseCancelOperation._get_transcoded_request(http_options, request) - - body = _BaseConfigRestTransport._BaseCancelOperation._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseConfigRestTransport._BaseCancelOperation._get_query_params_json(transcoded_request) - - 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.config_v1.ConfigClient.CancelOperation", - extra = { - "serviceName": "google.cloud.config.v1.Config", - "rpcName": "CancelOperation", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = ConfigRestTransport._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(_BaseConfigRestTransport._BaseDeleteOperation, ConfigRestStub): - def __hash__(self): - return hash("ConfigRestTransport.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 = _BaseConfigRestTransport._BaseDeleteOperation._get_http_options() - - request, metadata = self._interceptor.pre_delete_operation(request, metadata) - transcoded_request = _BaseConfigRestTransport._BaseDeleteOperation._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseConfigRestTransport._BaseDeleteOperation._get_query_params_json(transcoded_request) - - 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.config_v1.ConfigClient.DeleteOperation", - extra = { - "serviceName": "google.cloud.config.v1.Config", - "rpcName": "DeleteOperation", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = ConfigRestTransport._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(_BaseConfigRestTransport._BaseGetOperation, ConfigRestStub): - def __hash__(self): - return hash("ConfigRestTransport.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 = _BaseConfigRestTransport._BaseGetOperation._get_http_options() - - request, metadata = self._interceptor.pre_get_operation(request, metadata) - transcoded_request = _BaseConfigRestTransport._BaseGetOperation._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseConfigRestTransport._BaseGetOperation._get_query_params_json(transcoded_request) - - 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.config_v1.ConfigClient.GetOperation", - extra = { - "serviceName": "google.cloud.config.v1.Config", - "rpcName": "GetOperation", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = ConfigRestTransport._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.config_v1.ConfigAsyncClient.GetOperation", - extra = { - "serviceName": "google.cloud.config.v1.Config", - "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(_BaseConfigRestTransport._BaseListOperations, ConfigRestStub): - def __hash__(self): - return hash("ConfigRestTransport.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 = _BaseConfigRestTransport._BaseListOperations._get_http_options() - - request, metadata = self._interceptor.pre_list_operations(request, metadata) - transcoded_request = _BaseConfigRestTransport._BaseListOperations._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseConfigRestTransport._BaseListOperations._get_query_params_json(transcoded_request) - - 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.config_v1.ConfigClient.ListOperations", - extra = { - "serviceName": "google.cloud.config.v1.Config", - "rpcName": "ListOperations", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = ConfigRestTransport._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.config_v1.ConfigAsyncClient.ListOperations", - extra = { - "serviceName": "google.cloud.config.v1.Config", - "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__=( - 'ConfigRestTransport', -) diff --git a/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/transports/rest_base.py b/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/transports/rest_base.py deleted file mode 100644 index 08824caf9058..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/transports/rest_base.py +++ /dev/null @@ -1,1435 +0,0 @@ -# -*- 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. -# -import json # type: ignore -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.cloud.location import locations_pb2 # type: ignore -from .base import ConfigTransport, DEFAULT_CLIENT_INFO - -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union - - -from google.cloud.config_v1.types import config -from google.protobuf import empty_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore - - -class _BaseConfigRestTransport(ConfigTransport): - """Base REST backend transport for Config. - - 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 = 'config.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: 'config.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 _BaseCreateDeployment: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "deploymentId" : "", } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/locations/*}/deployments', - 'body': 'deployment', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = config.CreateDeploymentRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseConfigRestTransport._BaseCreateDeployment._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseCreatePreview: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/locations/*}/previews', - 'body': 'preview', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = config.CreatePreviewRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseConfigRestTransport._BaseCreatePreview._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseDeleteDeployment: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/deployments/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = config.DeleteDeploymentRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseConfigRestTransport._BaseDeleteDeployment._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseDeletePreview: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/previews/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = config.DeletePreviewRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseConfigRestTransport._BaseDeletePreview._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseDeleteStatefile: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{name=projects/*/locations/*/deployments/*}:deleteState', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = config.DeleteStatefileRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseConfigRestTransport._BaseDeleteStatefile._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseExportDeploymentStatefile: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/locations/*/deployments/*}:exportState', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = config.ExportDeploymentStatefileRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseConfigRestTransport._BaseExportDeploymentStatefile._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseExportLockInfo: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/deployments/*}:exportLock', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = config.ExportLockInfoRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseConfigRestTransport._BaseExportLockInfo._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseExportPreviewResult: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/locations/*/previews/*}:export', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = config.ExportPreviewResultRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseConfigRestTransport._BaseExportPreviewResult._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseExportRevisionStatefile: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/locations/*/deployments/*/revisions/*}:exportState', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = config.ExportRevisionStatefileRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseConfigRestTransport._BaseExportRevisionStatefile._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetDeployment: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/deployments/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = config.GetDeploymentRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseConfigRestTransport._BaseGetDeployment._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetPreview: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/previews/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = config.GetPreviewRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseConfigRestTransport._BaseGetPreview._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetResource: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/deployments/*/revisions/*/resources/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = config.GetResourceRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseConfigRestTransport._BaseGetResource._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetResourceChange: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/previews/*/resourceChanges/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = config.GetResourceChangeRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseConfigRestTransport._BaseGetResourceChange._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetResourceDrift: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/previews/*/resourceDrifts/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = config.GetResourceDriftRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseConfigRestTransport._BaseGetResourceDrift._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetRevision: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/deployments/*/revisions/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = config.GetRevisionRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseConfigRestTransport._BaseGetRevision._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetTerraformVersion: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/terraformVersions/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = config.GetTerraformVersionRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseConfigRestTransport._BaseGetTerraformVersion._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseImportStatefile: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/locations/*/deployments/*}:importState', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = config.ImportStatefileRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseConfigRestTransport._BaseImportStatefile._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseListDeployments: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/locations/*}/deployments', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = config.ListDeploymentsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseConfigRestTransport._BaseListDeployments._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseListPreviews: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/locations/*}/previews', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = config.ListPreviewsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseConfigRestTransport._BaseListPreviews._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseListResourceChanges: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/locations/*/previews/*}/resourceChanges', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = config.ListResourceChangesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseConfigRestTransport._BaseListResourceChanges._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseListResourceDrifts: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/locations/*/previews/*}/resourceDrifts', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = config.ListResourceDriftsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseConfigRestTransport._BaseListResourceDrifts._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseListResources: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/locations/*/deployments/*/revisions/*}/resources', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = config.ListResourcesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseConfigRestTransport._BaseListResources._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseListRevisions: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/locations/*/deployments/*}/revisions', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = config.ListRevisionsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseConfigRestTransport._BaseListRevisions._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseListTerraformVersions: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/locations/*}/terraformVersions', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = config.ListTerraformVersionsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseConfigRestTransport._BaseListTerraformVersions._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseLockDeployment: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{name=projects/*/locations/*/deployments/*}:lock', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = config.LockDeploymentRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseConfigRestTransport._BaseLockDeployment._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseUnlockDeployment: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{name=projects/*/locations/*/deployments/*}:unlock', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = config.UnlockDeploymentRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseConfigRestTransport._BaseUnlockDeployment._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseUpdateDeployment: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1/{deployment.name=projects/*/locations/*/deployments/*}', - 'body': 'deployment', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = config.UpdateDeploymentRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseConfigRestTransport._BaseUpdateDeployment._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - 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': '/v1/{name=projects/*/locations/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - return query_params - - 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': '/v1/{name=projects/*}/locations', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - return query_params - - 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': '/v1/{resource=projects/*/locations/*/deployments/*}:getIamPolicy', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - return query_params - - 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': '/v1/{resource=projects/*/locations/*/deployments/*}:setIamPolicy', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - body = json.dumps(transcoded_request['body']) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - return query_params - - 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': '/v1/{resource=projects/*/locations/*/deployments/*}:testIamPermissions', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - body = json.dumps(transcoded_request['body']) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - return query_params - - 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=projects/*/locations/*/operations/*}:cancel', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - body = json.dumps(transcoded_request['body']) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - return query_params - - 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': '/v1/{name=projects/*/locations/*/operations/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - return query_params - - 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=projects/*/locations/*/operations/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - return query_params - - 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': '/v1/{name=projects/*/locations/*}/operations', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - return query_params - - -__all__=( - '_BaseConfigRestTransport', -) diff --git a/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/types/__init__.py b/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/types/__init__.py deleted file mode 100644 index a569bc7349ae..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/types/__init__.py +++ /dev/null @@ -1,146 +0,0 @@ -# -*- 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. -# -from .config import ( - ApplyResults, - CreateDeploymentRequest, - CreatePreviewRequest, - DeleteDeploymentRequest, - DeletePreviewRequest, - DeleteStatefileRequest, - Deployment, - DeploymentOperationMetadata, - ExportDeploymentStatefileRequest, - ExportLockInfoRequest, - ExportPreviewResultRequest, - ExportPreviewResultResponse, - ExportRevisionStatefileRequest, - GetDeploymentRequest, - GetPreviewRequest, - GetResourceChangeRequest, - GetResourceDriftRequest, - GetResourceRequest, - GetRevisionRequest, - GetTerraformVersionRequest, - GitSource, - ImportStatefileRequest, - ListDeploymentsRequest, - ListDeploymentsResponse, - ListPreviewsRequest, - ListPreviewsResponse, - ListResourceChangesRequest, - ListResourceChangesResponse, - ListResourceDriftsRequest, - ListResourceDriftsResponse, - ListResourcesRequest, - ListResourcesResponse, - ListRevisionsRequest, - ListRevisionsResponse, - ListTerraformVersionsRequest, - ListTerraformVersionsResponse, - LockDeploymentRequest, - LockInfo, - OperationMetadata, - Preview, - PreviewArtifacts, - PreviewOperationMetadata, - PreviewResult, - PropertyChange, - PropertyDrift, - ProviderConfig, - Resource, - ResourceCAIInfo, - ResourceChange, - ResourceChangeTerraformInfo, - ResourceDrift, - ResourceDriftTerraformInfo, - ResourceTerraformInfo, - Revision, - Statefile, - TerraformBlueprint, - TerraformError, - TerraformOutput, - TerraformVariable, - TerraformVersion, - UnlockDeploymentRequest, - UpdateDeploymentRequest, - QuotaValidation, -) - -__all__ = ( - 'ApplyResults', - 'CreateDeploymentRequest', - 'CreatePreviewRequest', - 'DeleteDeploymentRequest', - 'DeletePreviewRequest', - 'DeleteStatefileRequest', - 'Deployment', - 'DeploymentOperationMetadata', - 'ExportDeploymentStatefileRequest', - 'ExportLockInfoRequest', - 'ExportPreviewResultRequest', - 'ExportPreviewResultResponse', - 'ExportRevisionStatefileRequest', - 'GetDeploymentRequest', - 'GetPreviewRequest', - 'GetResourceChangeRequest', - 'GetResourceDriftRequest', - 'GetResourceRequest', - 'GetRevisionRequest', - 'GetTerraformVersionRequest', - 'GitSource', - 'ImportStatefileRequest', - 'ListDeploymentsRequest', - 'ListDeploymentsResponse', - 'ListPreviewsRequest', - 'ListPreviewsResponse', - 'ListResourceChangesRequest', - 'ListResourceChangesResponse', - 'ListResourceDriftsRequest', - 'ListResourceDriftsResponse', - 'ListResourcesRequest', - 'ListResourcesResponse', - 'ListRevisionsRequest', - 'ListRevisionsResponse', - 'ListTerraformVersionsRequest', - 'ListTerraformVersionsResponse', - 'LockDeploymentRequest', - 'LockInfo', - 'OperationMetadata', - 'Preview', - 'PreviewArtifacts', - 'PreviewOperationMetadata', - 'PreviewResult', - 'PropertyChange', - 'PropertyDrift', - 'ProviderConfig', - 'Resource', - 'ResourceCAIInfo', - 'ResourceChange', - 'ResourceChangeTerraformInfo', - 'ResourceDrift', - 'ResourceDriftTerraformInfo', - 'ResourceTerraformInfo', - 'Revision', - 'Statefile', - 'TerraformBlueprint', - 'TerraformError', - 'TerraformOutput', - 'TerraformVariable', - 'TerraformVersion', - 'UnlockDeploymentRequest', - 'UpdateDeploymentRequest', - 'QuotaValidation', -) diff --git a/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/types/config.py b/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/types/config.py deleted file mode 100644 index b46aae6d4ca4..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/types/config.py +++ /dev/null @@ -1,3309 +0,0 @@ -# -*- 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. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.config.v1', - manifest={ - 'QuotaValidation', - 'Deployment', - 'TerraformBlueprint', - 'TerraformVariable', - 'ApplyResults', - 'TerraformOutput', - 'ListDeploymentsRequest', - 'ListDeploymentsResponse', - 'GetDeploymentRequest', - 'ListRevisionsRequest', - 'ListRevisionsResponse', - 'GetRevisionRequest', - 'CreateDeploymentRequest', - 'UpdateDeploymentRequest', - 'DeleteDeploymentRequest', - 'OperationMetadata', - 'Revision', - 'TerraformError', - 'GitSource', - 'DeploymentOperationMetadata', - 'Resource', - 'ResourceTerraformInfo', - 'ResourceCAIInfo', - 'GetResourceRequest', - 'ListResourcesRequest', - 'ListResourcesResponse', - 'Statefile', - 'ExportDeploymentStatefileRequest', - 'ExportRevisionStatefileRequest', - 'ImportStatefileRequest', - 'DeleteStatefileRequest', - 'LockDeploymentRequest', - 'UnlockDeploymentRequest', - 'ExportLockInfoRequest', - 'LockInfo', - 'Preview', - 'PreviewOperationMetadata', - 'PreviewArtifacts', - 'CreatePreviewRequest', - 'GetPreviewRequest', - 'ListPreviewsRequest', - 'ListPreviewsResponse', - 'DeletePreviewRequest', - 'ExportPreviewResultRequest', - 'ExportPreviewResultResponse', - 'PreviewResult', - 'GetTerraformVersionRequest', - 'ListTerraformVersionsRequest', - 'ListTerraformVersionsResponse', - 'TerraformVersion', - 'ResourceChangeTerraformInfo', - 'ResourceChange', - 'PropertyChange', - 'ListResourceChangesRequest', - 'ListResourceChangesResponse', - 'GetResourceChangeRequest', - 'ResourceDriftTerraformInfo', - 'ResourceDrift', - 'PropertyDrift', - 'ListResourceDriftsRequest', - 'ListResourceDriftsResponse', - 'GetResourceDriftRequest', - 'ProviderConfig', - }, -) - - -class QuotaValidation(proto.Enum): - r"""Enum values to control quota checks for resources in - terraform configuration files. - - Values: - QUOTA_VALIDATION_UNSPECIFIED (0): - The default value. - QuotaValidation on terraform configuration files - will be disabled in this case. - ENABLED (1): - Enable computing quotas for resources in - terraform configuration files to get visibility - on resources with insufficient quotas. - ENFORCED (2): - Enforce quota checks so deployment fails if - there isn't sufficient quotas available to - deploy resources in terraform configuration - files. - """ - QUOTA_VALIDATION_UNSPECIFIED = 0 - ENABLED = 1 - ENFORCED = 2 - - -class Deployment(proto.Message): - r"""A Deployment is a group of resources and configs managed and - provisioned by Infra Manager. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - terraform_blueprint (google.cloud.config_v1.types.TerraformBlueprint): - A blueprint described using Terraform's - HashiCorp Configuration Language as a root - module. - - This field is a member of `oneof`_ ``blueprint``. - name (str): - Identifier. Resource name of the deployment. Format: - ``projects/{project}/locations/{location}/deployments/{deployment}`` - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Time when the deployment was - created. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Time when the deployment was - last modified. - labels (MutableMapping[str, str]): - Optional. User-defined metadata for the - deployment. - state (google.cloud.config_v1.types.Deployment.State): - Output only. Current state of the deployment. - latest_revision (str): - Output only. Revision name that was most recently applied. - Format: - ``projects/{project}/locations/{location}/deployments/{deployment}/ revisions/{revision}`` - state_detail (str): - Output only. Additional information regarding - the current state. - error_code (google.cloud.config_v1.types.Deployment.ErrorCode): - Output only. Error code describing errors - that may have occurred. - delete_results (google.cloud.config_v1.types.ApplyResults): - Output only. Location of artifacts from a - DeleteDeployment operation. - delete_build (str): - Output only. Cloud Build instance UUID - associated with deleting this deployment. - delete_logs (str): - Output only. Location of Cloud Build logs in Google Cloud - Storage, populated when deleting this deployment. Format: - ``gs://{bucket}/{object}``. - tf_errors (MutableSequence[google.cloud.config_v1.types.TerraformError]): - Output only. Errors encountered when deleting this - deployment. Errors are truncated to 10 entries, see - ``delete_results`` and ``error_logs`` for full details. - error_logs (str): - Output only. Location of Terraform error logs in Google - Cloud Storage. Format: ``gs://{bucket}/{object}``. - artifacts_gcs_bucket (str): - Optional. User-defined location of Cloud Build logs and - artifacts in Google Cloud Storage. Format: - ``gs://{bucket}/{folder}`` - - A default bucket will be bootstrapped if the field is not - set or empty. Default bucket format: - ``gs://--blueprint-config`` - Constraints: - - - The bucket needs to be in the same project as the - deployment - - The path cannot be within the path of ``gcs_source`` - - The field cannot be updated, including changing its - presence - - This field is a member of `oneof`_ ``_artifacts_gcs_bucket``. - service_account (str): - Required. User-specified Service Account (SA) credentials to - be used when actuating resources. Format: - ``projects/{projectID}/serviceAccounts/{serviceAccount}`` - - This field is a member of `oneof`_ ``_service_account``. - import_existing_resources (bool): - By default, Infra Manager will return a - failure when Terraform encounters a 409 code - (resource conflict error) during actuation. If - this flag is set to true, Infra Manager will - instead attempt to automatically import the - resource into the Terraform state (for supported - resource types) and continue actuation. - - Not all resource types are supported, refer to - documentation. - - This field is a member of `oneof`_ ``_import_existing_resources``. - worker_pool (str): - Optional. The user-specified Cloud Build worker pool - resource in which the Cloud Build job will execute. Format: - ``projects/{project}/locations/{location}/workerPools/{workerPoolId}``. - If this field is unspecified, the default Cloud Build worker - pool will be used. - - This field is a member of `oneof`_ ``_worker_pool``. - lock_state (google.cloud.config_v1.types.Deployment.LockState): - Output only. Current lock state of the - deployment. - tf_version_constraint (str): - Optional. The user-specified Terraform - version constraint. Example: "=1.3.10". - - This field is a member of `oneof`_ ``_tf_version_constraint``. - tf_version (str): - Output only. The current Terraform version - set on the deployment. It is in the format of - "Major.Minor.Patch", for example, "1.3.10". - quota_validation (google.cloud.config_v1.types.QuotaValidation): - Optional. Input to control quota checks for - resources in terraform configuration files. - There are limited resources on which quota - validation applies. - annotations (MutableMapping[str, str]): - Optional. Arbitrary key-value metadata - storage e.g. to help client tools identify - deployments during automation. See - https://google.aip.dev/148#annotations for - details on format and size limitations. - provider_config (google.cloud.config_v1.types.ProviderConfig): - Optional. This field specifies the provider - configurations. - """ - class State(proto.Enum): - r"""Possible states of a deployment. - - Values: - STATE_UNSPECIFIED (0): - The default value. This value is used if the - state is omitted. - CREATING (1): - The deployment is being created. - ACTIVE (2): - The deployment is healthy. - UPDATING (3): - The deployment is being updated. - DELETING (4): - The deployment is being deleted. - FAILED (5): - The deployment has encountered an unexpected - error. - SUSPENDED (6): - The deployment is no longer being actively - reconciled. This may be the result of recovering - the project after deletion. - DELETED (7): - The deployment has been deleted. - """ - STATE_UNSPECIFIED = 0 - CREATING = 1 - ACTIVE = 2 - UPDATING = 3 - DELETING = 4 - FAILED = 5 - SUSPENDED = 6 - DELETED = 7 - - class ErrorCode(proto.Enum): - r"""Possible errors that can occur with deployments. - - Values: - ERROR_CODE_UNSPECIFIED (0): - No error code was specified. - REVISION_FAILED (1): - The revision failed. See Revision for more - details. - CLOUD_BUILD_PERMISSION_DENIED (3): - Cloud Build failed due to a permission issue. - DELETE_BUILD_API_FAILED (5): - Cloud Build job associated with a deployment - deletion could not be started. - DELETE_BUILD_RUN_FAILED (6): - Cloud Build job associated with a deployment - deletion was started but failed. - BUCKET_CREATION_PERMISSION_DENIED (7): - Cloud Storage bucket creation failed due to a - permission issue. - BUCKET_CREATION_FAILED (8): - Cloud Storage bucket creation failed due to - an issue unrelated to permissions. - """ - ERROR_CODE_UNSPECIFIED = 0 - REVISION_FAILED = 1 - CLOUD_BUILD_PERMISSION_DENIED = 3 - DELETE_BUILD_API_FAILED = 5 - DELETE_BUILD_RUN_FAILED = 6 - BUCKET_CREATION_PERMISSION_DENIED = 7 - BUCKET_CREATION_FAILED = 8 - - class LockState(proto.Enum): - r"""Possible lock states of a deployment. - - Values: - LOCK_STATE_UNSPECIFIED (0): - The default value. This value is used if the - lock state is omitted. - LOCKED (1): - The deployment is locked. - UNLOCKED (2): - The deployment is unlocked. - LOCKING (3): - The deployment is being locked. - UNLOCKING (4): - The deployment is being unlocked. - LOCK_FAILED (5): - The deployment has failed to lock. - UNLOCK_FAILED (6): - The deployment has failed to unlock. - """ - LOCK_STATE_UNSPECIFIED = 0 - LOCKED = 1 - UNLOCKED = 2 - LOCKING = 3 - UNLOCKING = 4 - LOCK_FAILED = 5 - UNLOCK_FAILED = 6 - - terraform_blueprint: 'TerraformBlueprint' = proto.Field( - proto.MESSAGE, - number=6, - oneof='blueprint', - message='TerraformBlueprint', - ) - 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, - ) - state: State = proto.Field( - proto.ENUM, - number=5, - enum=State, - ) - latest_revision: str = proto.Field( - proto.STRING, - number=7, - ) - state_detail: str = proto.Field( - proto.STRING, - number=9, - ) - error_code: ErrorCode = proto.Field( - proto.ENUM, - number=10, - enum=ErrorCode, - ) - delete_results: 'ApplyResults' = proto.Field( - proto.MESSAGE, - number=8, - message='ApplyResults', - ) - delete_build: str = proto.Field( - proto.STRING, - number=11, - ) - delete_logs: str = proto.Field( - proto.STRING, - number=12, - ) - tf_errors: MutableSequence['TerraformError'] = proto.RepeatedField( - proto.MESSAGE, - number=13, - message='TerraformError', - ) - error_logs: str = proto.Field( - proto.STRING, - number=14, - ) - artifacts_gcs_bucket: str = proto.Field( - proto.STRING, - number=15, - optional=True, - ) - service_account: str = proto.Field( - proto.STRING, - number=16, - optional=True, - ) - import_existing_resources: bool = proto.Field( - proto.BOOL, - number=17, - optional=True, - ) - worker_pool: str = proto.Field( - proto.STRING, - number=19, - optional=True, - ) - lock_state: LockState = proto.Field( - proto.ENUM, - number=20, - enum=LockState, - ) - tf_version_constraint: str = proto.Field( - proto.STRING, - number=21, - optional=True, - ) - tf_version: str = proto.Field( - proto.STRING, - number=22, - ) - quota_validation: 'QuotaValidation' = proto.Field( - proto.ENUM, - number=23, - enum='QuotaValidation', - ) - annotations: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=24, - ) - provider_config: 'ProviderConfig' = proto.Field( - proto.MESSAGE, - number=25, - message='ProviderConfig', - ) - - -class TerraformBlueprint(proto.Message): - r"""TerraformBlueprint describes the source of a Terraform root - module which describes the resources and configs to be deployed. - - 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: - gcs_source (str): - URI of an object in Google Cloud Storage. Format: - ``gs://{bucket}/{object}`` - - URI may also specify an object version for zipped objects. - Format: ``gs://{bucket}/{object}#{version}`` - - This field is a member of `oneof`_ ``source``. - git_source (google.cloud.config_v1.types.GitSource): - URI of a public Git repo. - - This field is a member of `oneof`_ ``source``. - input_values (MutableMapping[str, google.cloud.config_v1.types.TerraformVariable]): - Optional. Input variable values for the - Terraform blueprint. - """ - - gcs_source: str = proto.Field( - proto.STRING, - number=1, - oneof='source', - ) - git_source: 'GitSource' = proto.Field( - proto.MESSAGE, - number=2, - oneof='source', - message='GitSource', - ) - input_values: MutableMapping[str, 'TerraformVariable'] = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=4, - message='TerraformVariable', - ) - - -class TerraformVariable(proto.Message): - r"""A Terraform input variable. - - Attributes: - input_value (google.protobuf.struct_pb2.Value): - Optional. Input variable value. - """ - - input_value: struct_pb2.Value = proto.Field( - proto.MESSAGE, - number=5, - message=struct_pb2.Value, - ) - - -class ApplyResults(proto.Message): - r"""Outputs and artifacts from applying a deployment. - - Attributes: - content (str): - Location of a blueprint copy and other manifests in Google - Cloud Storage. Format: ``gs://{bucket}/{object}`` - artifacts (str): - Location of artifacts (e.g. logs) in Google Cloud Storage. - Format: ``gs://{bucket}/{object}`` - outputs (MutableMapping[str, google.cloud.config_v1.types.TerraformOutput]): - Map of output name to output info. - """ - - content: str = proto.Field( - proto.STRING, - number=1, - ) - artifacts: str = proto.Field( - proto.STRING, - number=2, - ) - outputs: MutableMapping[str, 'TerraformOutput'] = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=3, - message='TerraformOutput', - ) - - -class TerraformOutput(proto.Message): - r"""Describes a Terraform output. - - Attributes: - sensitive (bool): - Identifies whether Terraform has set this - output as a potential sensitive value. - value (google.protobuf.struct_pb2.Value): - Value of output. - """ - - sensitive: bool = proto.Field( - proto.BOOL, - number=1, - ) - value: struct_pb2.Value = proto.Field( - proto.MESSAGE, - number=2, - message=struct_pb2.Value, - ) - - -class ListDeploymentsRequest(proto.Message): - r""" - - Attributes: - parent (str): - Required. The parent in whose context the Deployments are - listed. The parent value is in the format: - 'projects/{project_id}/locations/{location}'. - page_size (int): - When requesting a page of resources, 'page_size' specifies - number of resources to return. If unspecified, at most 500 - will be returned. The maximum value is 1000. - page_token (str): - Token returned by previous call to - 'ListDeployments' which specifies the position - in the list from where to continue listing the - resources. - filter (str): - Lists the Deployments that match the filter expression. A - filter expression filters the resources listed in the - response. The expression must be of the form '{field} - {operator} {value}' where operators: '<', '>', '<=', '>=', - '!=', '=', ':' are supported (colon ':' represents a HAS - operator which is roughly synonymous with equality). {field} - can refer to a proto or JSON field, or a synthetic field. - Field names can be camelCase or snake_case. - - Examples: - - - Filter by name: name = - "projects/foo/locations/us-central1/deployments/bar - - - Filter by labels: - - - Resources that have a key called 'foo' labels.foo:\* - - Resources that have a key called 'foo' whose value is - 'bar' labels.foo = bar - - - Filter by state: - - - Deployments in CREATING state. state=CREATING - order_by (str): - Field to use to sort the list. - """ - - 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 ListDeploymentsResponse(proto.Message): - r""" - - Attributes: - deployments (MutableSequence[google.cloud.config_v1.types.Deployment]): - List of [Deployment][google.cloud.config.v1.Deployment]s. - next_page_token (str): - Token to be supplied to the next ListDeployments request via - ``page_token`` to obtain the next set of results. - unreachable (MutableSequence[str]): - Locations that could not be reached. - """ - - @property - def raw_page(self): - return self - - deployments: MutableSequence['Deployment'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Deployment', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - unreachable: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - - -class GetDeploymentRequest(proto.Message): - r""" - - Attributes: - name (str): - Required. The name of the deployment. Format: - 'projects/{project_id}/locations/{location}/deployments/{deployment}'. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListRevisionsRequest(proto.Message): - r"""A request to list Revisions passed to a 'ListRevisions' call. - - Attributes: - parent (str): - Required. The parent in whose context the Revisions are - listed. The parent value is in the format: - 'projects/{project_id}/locations/{location}/deployments/{deployment}'. - page_size (int): - When requesting a page of resources, ``page_size`` specifies - number of resources to return. If unspecified, at most 500 - will be returned. The maximum value is 1000. - page_token (str): - Token returned by previous call to - 'ListRevisions' which specifies the position in - the list from where to continue listing the - resources. - filter (str): - Lists the Revisions that match the filter expression. A - filter expression filters the resources listed in the - response. The expression must be of the form '{field} - {operator} {value}' where operators: '<', '>', '<=', '>=', - '!=', '=', ':' are supported (colon ':' represents a HAS - operator which is roughly synonymous with equality). {field} - can refer to a proto or JSON field, or a synthetic field. - Field names can be camelCase or snake_case. - - Examples: - - - Filter by name: name = - "projects/foo/locations/us-central1/deployments/dep/revisions/bar - - - Filter by labels: - - - Resources that have a key called 'foo' labels.foo:\* - - Resources that have a key called 'foo' whose value is - 'bar' labels.foo = bar - - - Filter by state: - - - Revisions in CREATING state. state=CREATING - order_by (str): - Field to use to sort the list. - """ - - 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 ListRevisionsResponse(proto.Message): - r"""A response to a 'ListRevisions' call. Contains a list of - Revisions. - - Attributes: - revisions (MutableSequence[google.cloud.config_v1.types.Revision]): - List of [Revision][google.cloud.config.v1.Revision]s. - next_page_token (str): - A token to request the next page of resources - from the 'ListRevisions' method. The value of an - empty string means that there are no more - resources to return. - unreachable (MutableSequence[str]): - Locations that could not be reached. - """ - - @property - def raw_page(self): - return self - - revisions: MutableSequence['Revision'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Revision', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - unreachable: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - - -class GetRevisionRequest(proto.Message): - r"""A request to get a Revision from a 'GetRevision' call. - - Attributes: - name (str): - Required. The name of the Revision in the format: - 'projects/{project_id}/locations/{location}/deployments/{deployment}/revisions/{revision}'. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class CreateDeploymentRequest(proto.Message): - r""" - - Attributes: - parent (str): - Required. The parent in whose context the Deployment is - created. The parent value is in the format: - 'projects/{project_id}/locations/{location}'. - deployment_id (str): - Required. The Deployment ID. - deployment (google.cloud.config_v1.types.Deployment): - Required. [Deployment][google.cloud.config.v1.Deployment] - 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 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, - ) - deployment_id: str = proto.Field( - proto.STRING, - number=2, - ) - deployment: 'Deployment' = proto.Field( - proto.MESSAGE, - number=3, - message='Deployment', - ) - request_id: str = proto.Field( - proto.STRING, - number=4, - ) - - -class UpdateDeploymentRequest(proto.Message): - r""" - - Attributes: - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Optional. Field mask used to specify the fields to be - overwritten in the Deployment 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. - deployment (google.cloud.config_v1.types.Deployment): - Required. [Deployment][google.cloud.config.v1.Deployment] to - update. - - The deployment's ``name`` field is used to identify the - resource to be updated. Format: - ``projects/{project}/locations/{location}/deployments/{deployment}`` - 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, - ) - deployment: 'Deployment' = proto.Field( - proto.MESSAGE, - number=2, - message='Deployment', - ) - request_id: str = proto.Field( - proto.STRING, - number=3, - ) - - -class DeleteDeploymentRequest(proto.Message): - r""" - - Attributes: - name (str): - Required. The name of the Deployment in the format: - 'projects/{project_id}/locations/{location}/deployments/{deployment}'. - 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 revisions for - this deployment will also be deleted. - (Otherwise, the request will only work if the - deployment has no revisions.) - delete_policy (google.cloud.config_v1.types.DeleteDeploymentRequest.DeletePolicy): - Optional. Policy on how resources actuated by - the deployment should be deleted. If - unspecified, the default behavior is to delete - the underlying resources. - """ - class DeletePolicy(proto.Enum): - r"""Policy on how resources actuated by the deployment should be - deleted. - - Values: - DELETE_POLICY_UNSPECIFIED (0): - Unspecified policy, resources will be - deleted. - DELETE (1): - Deletes resources actuated by the deployment. - ABANDON (2): - Abandons resources and only deletes the - deployment and its metadata. - """ - DELETE_POLICY_UNSPECIFIED = 0 - DELETE = 1 - ABANDON = 2 - - 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, - ) - delete_policy: DeletePolicy = proto.Field( - proto.ENUM, - number=4, - enum=DeletePolicy, - ) - - -class OperationMetadata(proto.Message): - r"""Represents the metadata of the long-running operation. - - 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: - deployment_metadata (google.cloud.config_v1.types.DeploymentOperationMetadata): - Output only. Metadata about the deployment - operation state. - - This field is a member of `oneof`_ ``resource_metadata``. - preview_metadata (google.cloud.config_v1.types.PreviewOperationMetadata): - Output only. Metadata about the preview - operation state. - - This field is a member of `oneof`_ ``resource_metadata``. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Time when the operation was - created. - end_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Time when 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. - """ - - deployment_metadata: 'DeploymentOperationMetadata' = proto.Field( - proto.MESSAGE, - number=8, - oneof='resource_metadata', - message='DeploymentOperationMetadata', - ) - preview_metadata: 'PreviewOperationMetadata' = proto.Field( - proto.MESSAGE, - number=9, - oneof='resource_metadata', - message='PreviewOperationMetadata', - ) - 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 Revision(proto.Message): - r"""A child resource of a Deployment generated by a - 'CreateDeployment' or 'UpdateDeployment' call. Each Revision - contains metadata pertaining to a snapshot of a particular - Deployment. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - terraform_blueprint (google.cloud.config_v1.types.TerraformBlueprint): - Output only. A blueprint described using - Terraform's HashiCorp Configuration Language as - a root module. - - This field is a member of `oneof`_ ``blueprint``. - name (str): - Revision name. Format: - ``projects/{project}/locations/{location}/deployments/{deployment}/ revisions/{revision}`` - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Time when the revision was - created. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Time when the revision was last - modified. - action (google.cloud.config_v1.types.Revision.Action): - Output only. The action which created this - revision - state (google.cloud.config_v1.types.Revision.State): - Output only. Current state of the revision. - apply_results (google.cloud.config_v1.types.ApplyResults): - Output only. Outputs and artifacts from - applying a deployment. - state_detail (str): - Output only. Additional info regarding the - current state. - error_code (google.cloud.config_v1.types.Revision.ErrorCode): - Output only. Code describing any errors that - may have occurred. - build (str): - Output only. Cloud Build instance UUID - associated with this revision. - logs (str): - Output only. Location of Revision operation logs in - ``gs://{bucket}/{object}`` format. - tf_errors (MutableSequence[google.cloud.config_v1.types.TerraformError]): - Output only. Errors encountered when creating or updating - this deployment. Errors are truncated to 10 entries, see - ``delete_results`` and ``error_logs`` for full details. - error_logs (str): - Output only. Location of Terraform error logs in Google - Cloud Storage. Format: ``gs://{bucket}/{object}``. - service_account (str): - Output only. User-specified Service Account (SA) to be used - as credential to manage resources. Format: - ``projects/{projectID}/serviceAccounts/{serviceAccount}`` - import_existing_resources (bool): - Output only. By default, Infra Manager will - return a failure when Terraform encounters a 409 - code (resource conflict error) during actuation. - If this flag is set to true, Infra Manager will - instead attempt to automatically import the - resource into the Terraform state (for supported - resource types) and continue actuation. - - Not all resource types are supported, refer to - documentation. - worker_pool (str): - Output only. The user-specified Cloud Build worker pool - resource in which the Cloud Build job will execute. Format: - ``projects/{project}/locations/{location}/workerPools/{workerPoolId}``. - If this field is unspecified, the default Cloud Build worker - pool will be used. - tf_version_constraint (str): - Output only. The user-specified Terraform - version constraint. Example: "=1.3.10". - tf_version (str): - Output only. The version of Terraform used to - create the Revision. It is in the format of - "Major.Minor.Patch", for example, "1.3.10". - quota_validation_results (str): - Output only. Cloud Storage path containing quota validation - results. This field is set when a user sets - Deployment.quota_validation field to ENABLED or ENFORCED. - Format: ``gs://{bucket}/{object}``. - quota_validation (google.cloud.config_v1.types.QuotaValidation): - Optional. Input to control quota checks for - resources in terraform configuration files. - There are limited resources on which quota - validation applies. - provider_config (google.cloud.config_v1.types.ProviderConfig): - Output only. This field specifies the - provider configurations. - """ - class Action(proto.Enum): - r"""Actions that generate a revision. - - Values: - ACTION_UNSPECIFIED (0): - The default value. This value is used if the - action is omitted. - CREATE (1): - The revision was generated by creating a - deployment. - UPDATE (2): - The revision was generated by updating a - deployment. - DELETE (3): - The revision was deleted. - """ - ACTION_UNSPECIFIED = 0 - CREATE = 1 - UPDATE = 2 - DELETE = 3 - - class State(proto.Enum): - r"""Possible states of a revision. - - Values: - STATE_UNSPECIFIED (0): - The default value. This value is used if the - state is omitted. - APPLYING (1): - The revision is being applied. - APPLIED (2): - The revision was applied successfully. - FAILED (3): - The revision could not be applied - successfully. - """ - STATE_UNSPECIFIED = 0 - APPLYING = 1 - APPLIED = 2 - FAILED = 3 - - class ErrorCode(proto.Enum): - r"""Possible errors if Revision could not be created or updated - successfully. - - Values: - ERROR_CODE_UNSPECIFIED (0): - No error code was specified. - CLOUD_BUILD_PERMISSION_DENIED (1): - Cloud Build failed due to a permission issue. - APPLY_BUILD_API_FAILED (4): - Cloud Build job associated with creating or - updating a deployment could not be started. - APPLY_BUILD_RUN_FAILED (5): - Cloud Build job associated with creating or - updating a deployment was started but failed. - QUOTA_VALIDATION_FAILED (7): - quota validation failed for one or more - resources in terraform configuration files. - """ - ERROR_CODE_UNSPECIFIED = 0 - CLOUD_BUILD_PERMISSION_DENIED = 1 - APPLY_BUILD_API_FAILED = 4 - APPLY_BUILD_RUN_FAILED = 5 - QUOTA_VALIDATION_FAILED = 7 - - terraform_blueprint: 'TerraformBlueprint' = proto.Field( - proto.MESSAGE, - number=6, - oneof='blueprint', - message='TerraformBlueprint', - ) - 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, - ) - action: Action = proto.Field( - proto.ENUM, - number=4, - enum=Action, - ) - state: State = proto.Field( - proto.ENUM, - number=5, - enum=State, - ) - apply_results: 'ApplyResults' = proto.Field( - proto.MESSAGE, - number=7, - message='ApplyResults', - ) - state_detail: str = proto.Field( - proto.STRING, - number=8, - ) - error_code: ErrorCode = proto.Field( - proto.ENUM, - number=9, - enum=ErrorCode, - ) - build: str = proto.Field( - proto.STRING, - number=10, - ) - logs: str = proto.Field( - proto.STRING, - number=11, - ) - tf_errors: MutableSequence['TerraformError'] = proto.RepeatedField( - proto.MESSAGE, - number=12, - message='TerraformError', - ) - error_logs: str = proto.Field( - proto.STRING, - number=13, - ) - service_account: str = proto.Field( - proto.STRING, - number=14, - ) - import_existing_resources: bool = proto.Field( - proto.BOOL, - number=15, - ) - worker_pool: str = proto.Field( - proto.STRING, - number=17, - ) - tf_version_constraint: str = proto.Field( - proto.STRING, - number=18, - ) - tf_version: str = proto.Field( - proto.STRING, - number=19, - ) - quota_validation_results: str = proto.Field( - proto.STRING, - number=29, - ) - quota_validation: 'QuotaValidation' = proto.Field( - proto.ENUM, - number=20, - enum='QuotaValidation', - ) - provider_config: 'ProviderConfig' = proto.Field( - proto.MESSAGE, - number=21, - message='ProviderConfig', - ) - - -class TerraformError(proto.Message): - r"""Errors encountered during actuation using Terraform - - Attributes: - resource_address (str): - Address of the resource associated with the error, e.g. - ``google_compute_network.vpc_network``. - http_response_code (int): - HTTP response code returned from Google Cloud - Platform APIs when Terraform fails to provision - the resource. If unset or 0, no HTTP response - code was returned by Terraform. - error_description (str): - A human-readable error description. - error (google.rpc.status_pb2.Status): - Output only. Original error response from - underlying Google API, if available. - """ - - resource_address: str = proto.Field( - proto.STRING, - number=1, - ) - http_response_code: int = proto.Field( - proto.INT32, - number=2, - ) - error_description: str = proto.Field( - proto.STRING, - number=3, - ) - error: status_pb2.Status = proto.Field( - proto.MESSAGE, - number=4, - message=status_pb2.Status, - ) - - -class GitSource(proto.Message): - r"""A set of files in a Git repository. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - repo (str): - Optional. Repository URL. - Example: - 'https://github.com/kubernetes/examples.git' - - This field is a member of `oneof`_ ``_repo``. - directory (str): - Optional. Subdirectory inside the repository. - Example: 'staging/my-package' - - This field is a member of `oneof`_ ``_directory``. - ref (str): - Optional. Git reference (e.g. branch or tag). - - This field is a member of `oneof`_ ``_ref``. - """ - - repo: str = proto.Field( - proto.STRING, - number=1, - optional=True, - ) - directory: str = proto.Field( - proto.STRING, - number=2, - optional=True, - ) - ref: str = proto.Field( - proto.STRING, - number=3, - optional=True, - ) - - -class DeploymentOperationMetadata(proto.Message): - r"""Ephemeral metadata content describing the state of a - deployment operation. - - Attributes: - step (google.cloud.config_v1.types.DeploymentOperationMetadata.DeploymentStep): - The current step the deployment operation is - running. - apply_results (google.cloud.config_v1.types.ApplyResults): - Outputs and artifacts from applying a - deployment. - build (str): - Output only. Cloud Build instance UUID - associated with this operation. - logs (str): - Output only. Location of Deployment operations logs in - ``gs://{bucket}/{object}`` format. - """ - class DeploymentStep(proto.Enum): - r"""The possible steps a deployment may be running. - - Values: - DEPLOYMENT_STEP_UNSPECIFIED (0): - Unspecified deployment step - PREPARING_STORAGE_BUCKET (1): - Infra Manager is creating a Google Cloud - Storage bucket to store artifacts and metadata - about the deployment and revision - DOWNLOADING_BLUEPRINT (2): - Downloading the blueprint onto the Google - Cloud Storage bucket - RUNNING_TF_INIT (3): - Initializing Terraform using ``terraform init`` - RUNNING_TF_PLAN (4): - Running ``terraform plan`` - RUNNING_TF_APPLY (5): - Actuating resources using Terraform using - ``terraform apply`` - RUNNING_TF_DESTROY (6): - Destroying resources using Terraform using - ``terraform destroy`` - RUNNING_TF_VALIDATE (7): - Validating the uploaded TF state file when - unlocking a deployment - UNLOCKING_DEPLOYMENT (8): - Unlocking a deployment - SUCCEEDED (9): - Operation was successful - FAILED (10): - Operation failed - VALIDATING_REPOSITORY (11): - Validating the provided repository. - RUNNING_QUOTA_VALIDATION (12): - Running quota validation - """ - DEPLOYMENT_STEP_UNSPECIFIED = 0 - PREPARING_STORAGE_BUCKET = 1 - DOWNLOADING_BLUEPRINT = 2 - RUNNING_TF_INIT = 3 - RUNNING_TF_PLAN = 4 - RUNNING_TF_APPLY = 5 - RUNNING_TF_DESTROY = 6 - RUNNING_TF_VALIDATE = 7 - UNLOCKING_DEPLOYMENT = 8 - SUCCEEDED = 9 - FAILED = 10 - VALIDATING_REPOSITORY = 11 - RUNNING_QUOTA_VALIDATION = 12 - - step: DeploymentStep = proto.Field( - proto.ENUM, - number=1, - enum=DeploymentStep, - ) - apply_results: 'ApplyResults' = proto.Field( - proto.MESSAGE, - number=2, - message='ApplyResults', - ) - build: str = proto.Field( - proto.STRING, - number=3, - ) - logs: str = proto.Field( - proto.STRING, - number=4, - ) - - -class Resource(proto.Message): - r"""Resource represents a Google Cloud Platform resource actuated - by IM. Resources are child resources of Revisions. - - Attributes: - name (str): - Output only. Resource name. Format: - ``projects/{project}/locations/{location}/deployments/{deployment}/revisions/{revision}/resources/{resource}`` - terraform_info (google.cloud.config_v1.types.ResourceTerraformInfo): - Output only. Terraform-specific info if this - resource was created using Terraform. - cai_assets (MutableMapping[str, google.cloud.config_v1.types.ResourceCAIInfo]): - Output only. Map of Cloud Asset Inventory - (CAI) type to CAI info (e.g. CAI ID). CAI type - format follows - https://cloud.google.com/asset-inventory/docs/supported-asset-types - intent (google.cloud.config_v1.types.Resource.Intent): - Output only. Intent of the resource. - state (google.cloud.config_v1.types.Resource.State): - Output only. Current state of the resource. - """ - class Intent(proto.Enum): - r"""Possible intent of the resource. - - Values: - INTENT_UNSPECIFIED (0): - The default value. This value is used if the - intent is omitted. - CREATE (1): - Infra Manager will create this Resource. - UPDATE (2): - Infra Manager will update this Resource. - DELETE (3): - Infra Manager will delete this Resource. - RECREATE (4): - Infra Manager will destroy and recreate this - Resource. - UNCHANGED (5): - Infra Manager will leave this Resource - untouched. - """ - INTENT_UNSPECIFIED = 0 - CREATE = 1 - UPDATE = 2 - DELETE = 3 - RECREATE = 4 - UNCHANGED = 5 - - class State(proto.Enum): - r"""Possible states of a resource. - - Values: - STATE_UNSPECIFIED (0): - The default value. This value is used if the - state is omitted. - PLANNED (1): - Resource has been planned for reconcile. - IN_PROGRESS (2): - Resource is actively reconciling into the - intended state. - RECONCILED (3): - Resource has reconciled to intended state. - FAILED (4): - Resource failed to reconcile. - """ - STATE_UNSPECIFIED = 0 - PLANNED = 1 - IN_PROGRESS = 2 - RECONCILED = 3 - FAILED = 4 - - name: str = proto.Field( - proto.STRING, - number=1, - ) - terraform_info: 'ResourceTerraformInfo' = proto.Field( - proto.MESSAGE, - number=2, - message='ResourceTerraformInfo', - ) - cai_assets: MutableMapping[str, 'ResourceCAIInfo'] = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=3, - message='ResourceCAIInfo', - ) - intent: Intent = proto.Field( - proto.ENUM, - number=4, - enum=Intent, - ) - state: State = proto.Field( - proto.ENUM, - number=5, - enum=State, - ) - - -class ResourceTerraformInfo(proto.Message): - r"""Terraform info of a Resource. - - Attributes: - address (str): - TF resource address that uniquely identifies - this resource within this deployment. - type_ (str): - TF resource type - id (str): - ID attribute of the TF resource - """ - - address: str = proto.Field( - proto.STRING, - number=1, - ) - type_: str = proto.Field( - proto.STRING, - number=2, - ) - id: str = proto.Field( - proto.STRING, - number=3, - ) - - -class ResourceCAIInfo(proto.Message): - r"""CAI info of a Resource. - - Attributes: - full_resource_name (str): - CAI resource name in the format following - https://cloud.google.com/apis/design/resource_names#full_resource_name - """ - - full_resource_name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class GetResourceRequest(proto.Message): - r"""A request to get a Resource from a 'GetResource' call. - - Attributes: - name (str): - Required. The name of the Resource in the format: - 'projects/{project_id}/locations/{location}/deployments/{deployment}/revisions/{revision}/resource/{resource}'. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListResourcesRequest(proto.Message): - r"""A request to list Resources passed to a 'ListResources' call. - - Attributes: - parent (str): - Required. The parent in whose context the Resources are - listed. The parent value is in the format: - 'projects/{project_id}/locations/{location}/deployments/{deployment}/revisions/{revision}'. - page_size (int): - When requesting a page of resources, 'page_size' specifies - number of resources to return. If unspecified, at most 500 - will be returned. The maximum value is 1000. - page_token (str): - Token returned by previous call to - 'ListResources' which specifies the position in - the list from where to continue listing the - resources. - filter (str): - Lists the Resources that match the filter expression. A - filter expression filters the resources listed in the - response. The expression must be of the form '{field} - {operator} {value}' where operators: '<', '>', '<=', '>=', - '!=', '=', ':' are supported (colon ':' represents a HAS - operator which is roughly synonymous with equality). {field} - can refer to a proto or JSON field, or a synthetic field. - Field names can be camelCase or snake_case. - - Examples: - - - Filter by name: name = - "projects/foo/locations/us-central1/deployments/dep/revisions/bar/resources/baz - order_by (str): - Field to use to sort the list. - """ - - 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 ListResourcesResponse(proto.Message): - r"""A response to a 'ListResources' call. Contains a list of - Resources. - - Attributes: - resources (MutableSequence[google.cloud.config_v1.types.Resource]): - List of [Resources][google.cloud.config.v1.Resource]. - next_page_token (str): - A token to request the next page of resources - from the 'ListResources' method. The value of an - empty string means that there are no more - resources to return. - unreachable (MutableSequence[str]): - Locations that could not be reached. - """ - - @property - def raw_page(self): - return self - - resources: MutableSequence['Resource'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Resource', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - unreachable: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - - -class Statefile(proto.Message): - r"""Contains info about a Terraform state file - - Attributes: - signed_uri (str): - Output only. Cloud Storage signed URI used - for downloading or uploading the state file. - """ - - signed_uri: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ExportDeploymentStatefileRequest(proto.Message): - r"""A request to export a state file passed to a - 'ExportDeploymentStatefile' call. - - Attributes: - parent (str): - Required. The parent in whose context the statefile is - listed. The parent value is in the format: - 'projects/{project_id}/locations/{location}/deployments/{deployment}'. - draft (bool): - Optional. If this flag is set to true, the - exported deployment state file will be the draft - state. This will enable the draft file to be - validated before copying it over to the working - state on unlock. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - draft: bool = proto.Field( - proto.BOOL, - number=3, - ) - - -class ExportRevisionStatefileRequest(proto.Message): - r"""A request to export a state file passed to a - 'ExportRevisionStatefile' call. - - Attributes: - parent (str): - Required. The parent in whose context the statefile is - listed. The parent value is in the format: - 'projects/{project_id}/locations/{location}/deployments/{deployment}/revisions/{revision}'. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ImportStatefileRequest(proto.Message): - r"""A request to import a state file passed to a - 'ImportStatefile' call. - - Attributes: - parent (str): - Required. The parent in whose context the statefile is - listed. The parent value is in the format: - 'projects/{project_id}/locations/{location}/deployments/{deployment}'. - lock_id (int): - Required. Lock ID of the lock file to verify - that the user who is importing the state file - previously locked the Deployment. - skip_draft (bool): - Optional. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - lock_id: int = proto.Field( - proto.INT64, - number=2, - ) - skip_draft: bool = proto.Field( - proto.BOOL, - number=3, - ) - - -class DeleteStatefileRequest(proto.Message): - r"""A request to delete a state file passed to a - 'DeleteStatefile' call. - - Attributes: - name (str): - Required. The name of the deployment in the format: - 'projects/{project_id}/locations/{location}/deployments/{deployment}'. - lock_id (int): - Required. Lock ID of the lock file to verify - that the user who is deleting the state file - previously locked the Deployment. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - lock_id: int = proto.Field( - proto.INT64, - number=2, - ) - - -class LockDeploymentRequest(proto.Message): - r"""A request to lock a deployment passed to a 'LockDeployment' - call. - - Attributes: - name (str): - Required. The name of the deployment in the format: - 'projects/{project_id}/locations/{location}/deployments/{deployment}'. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class UnlockDeploymentRequest(proto.Message): - r"""A request to unlock a state file passed to a - 'UnlockDeployment' call. - - Attributes: - name (str): - Required. The name of the deployment in the format: - 'projects/{project_id}/locations/{location}/deployments/{deployment}'. - lock_id (int): - Required. Lock ID of the lock file to be - unlocked. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - lock_id: int = proto.Field( - proto.INT64, - number=2, - ) - - -class ExportLockInfoRequest(proto.Message): - r"""A request to get a state file lock info passed to a - 'ExportLockInfo' call. - - Attributes: - name (str): - Required. The name of the deployment in the format: - 'projects/{project_id}/locations/{location}/deployments/{deployment}'. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class LockInfo(proto.Message): - r"""Details about the lock which locked the deployment. - - Attributes: - lock_id (int): - Unique ID for the lock to be overridden with - generation ID in the backend. - operation (str): - Terraform operation, provided by the caller. - info (str): - Extra information to store with the lock, - provided by the caller. - who (str): - user@hostname when available - version (str): - Terraform version - create_time (google.protobuf.timestamp_pb2.Timestamp): - Time that the lock was taken. - """ - - lock_id: int = proto.Field( - proto.INT64, - number=1, - ) - operation: str = proto.Field( - proto.STRING, - number=2, - ) - info: str = proto.Field( - proto.STRING, - number=3, - ) - who: str = proto.Field( - proto.STRING, - number=4, - ) - version: str = proto.Field( - proto.STRING, - number=5, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=6, - message=timestamp_pb2.Timestamp, - ) - - -class Preview(proto.Message): - r"""A preview represents a set of actions Infra Manager would - perform to move the resources towards the desired state as - specified in the configuration. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - terraform_blueprint (google.cloud.config_v1.types.TerraformBlueprint): - The terraform blueprint to preview. - - This field is a member of `oneof`_ ``blueprint``. - name (str): - Identifier. Resource name of the preview. Resource name can - be user provided or server generated ID if unspecified. - Format: - ``projects/{project}/locations/{location}/previews/{preview}`` - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Time the preview was created. - labels (MutableMapping[str, str]): - Optional. User-defined labels for the - preview. - state (google.cloud.config_v1.types.Preview.State): - Output only. Current state of the preview. - deployment (str): - Optional. Optional deployment reference. If - specified, the preview will be performed using - the provided deployment's current state and use - any relevant fields from the deployment unless - explicitly specified in the preview create - request. - preview_mode (google.cloud.config_v1.types.Preview.PreviewMode): - Optional. Current mode of preview. - service_account (str): - Required. User-specified Service Account (SA) credentials to - be used when previewing resources. Format: - ``projects/{projectID}/serviceAccounts/{serviceAccount}`` - artifacts_gcs_bucket (str): - Optional. User-defined location of Cloud Build logs, - artifacts, and in Google Cloud Storage. Format: - ``gs://{bucket}/{folder}`` A default bucket will be - bootstrapped if the field is not set or empty Default Bucket - Format: ``gs://--blueprint-config`` - Constraints: - - - The bucket needs to be in the same project as the - deployment - - The path cannot be within the path of ``gcs_source`` If - omitted and deployment resource ref provided has - artifacts_gcs_bucket defined, that artifact bucket is - used. - - This field is a member of `oneof`_ ``_artifacts_gcs_bucket``. - worker_pool (str): - Optional. The user-specified Worker Pool resource in which - the Cloud Build job will execute. Format - projects/{project}/locations/{location}/workerPools/{workerPoolId} - If this field is unspecified, the default Cloud Build worker - pool will be used. If omitted and deployment resource ref - provided has worker_pool defined, that worker pool is used. - - This field is a member of `oneof`_ ``_worker_pool``. - error_code (google.cloud.config_v1.types.Preview.ErrorCode): - Output only. Code describing any errors that - may have occurred. - error_status (google.rpc.status_pb2.Status): - Output only. Additional information regarding - the current state. - build (str): - Output only. Cloud Build instance UUID - associated with this preview. - tf_errors (MutableSequence[google.cloud.config_v1.types.TerraformError]): - Output only. Summary of errors encountered - during Terraform preview. It has a size limit of - 10, i.e. only top 10 errors will be summarized - here. - error_logs (str): - Output only. Link to tf-error.ndjson file, which contains - the full list of the errors encountered during a Terraform - preview. Format: ``gs://{bucket}/{object}``. - preview_artifacts (google.cloud.config_v1.types.PreviewArtifacts): - Output only. Artifacts from preview. - logs (str): - Output only. Location of preview logs in - ``gs://{bucket}/{object}`` format. - tf_version (str): - Output only. The current Terraform version - set on the preview. It is in the format of - "Major.Minor.Patch", for example, "1.3.10". - tf_version_constraint (str): - Optional. The user-specified Terraform - version constraint. Example: "=1.3.10". - - This field is a member of `oneof`_ ``_tf_version_constraint``. - annotations (MutableMapping[str, str]): - Optional. Arbitrary key-value metadata - storage e.g. to help client tools identify - preview during automation. See - https://google.aip.dev/148#annotations for - details on format and size limitations. - provider_config (google.cloud.config_v1.types.ProviderConfig): - Optional. This field specifies the provider - configurations. - """ - class State(proto.Enum): - r"""Possible states of a preview. - - Values: - STATE_UNSPECIFIED (0): - The default value. This value is used if the - state is unknown. - CREATING (1): - The preview is being created. - SUCCEEDED (2): - The preview has succeeded. - APPLYING (3): - The preview is being applied. - STALE (4): - The preview is stale. A preview can become - stale if a revision has been applied after this - preview was created. - DELETING (5): - The preview is being deleted. - FAILED (6): - The preview has encountered an unexpected - error. - DELETED (7): - The preview has been deleted. - """ - STATE_UNSPECIFIED = 0 - CREATING = 1 - SUCCEEDED = 2 - APPLYING = 3 - STALE = 4 - DELETING = 5 - FAILED = 6 - DELETED = 7 - - class PreviewMode(proto.Enum): - r"""Preview mode provides options for customizing preview - operations. - - Values: - PREVIEW_MODE_UNSPECIFIED (0): - Unspecified policy, default mode will be - used. - DEFAULT (1): - DEFAULT mode generates an execution plan for - reconciling current resource state into expected - resource state. - DELETE (2): - DELETE mode generates as execution plan for - destroying current resources. - """ - PREVIEW_MODE_UNSPECIFIED = 0 - DEFAULT = 1 - DELETE = 2 - - class ErrorCode(proto.Enum): - r"""Possible errors that can occur with previews. - - Values: - ERROR_CODE_UNSPECIFIED (0): - No error code was specified. - CLOUD_BUILD_PERMISSION_DENIED (1): - Cloud Build failed due to a permissions - issue. - BUCKET_CREATION_PERMISSION_DENIED (2): - Cloud Storage bucket failed to create due to - a permissions issue. - BUCKET_CREATION_FAILED (3): - Cloud Storage bucket failed for a - non-permissions-related issue. - DEPLOYMENT_LOCK_ACQUIRE_FAILED (4): - Acquiring lock on provided deployment - reference failed. - PREVIEW_BUILD_API_FAILED (5): - Preview encountered an error when trying to - access Cloud Build API. - PREVIEW_BUILD_RUN_FAILED (6): - Preview created a build but build failed and - logs were generated. - """ - ERROR_CODE_UNSPECIFIED = 0 - CLOUD_BUILD_PERMISSION_DENIED = 1 - BUCKET_CREATION_PERMISSION_DENIED = 2 - BUCKET_CREATION_FAILED = 3 - DEPLOYMENT_LOCK_ACQUIRE_FAILED = 4 - PREVIEW_BUILD_API_FAILED = 5 - PREVIEW_BUILD_RUN_FAILED = 6 - - terraform_blueprint: 'TerraformBlueprint' = proto.Field( - proto.MESSAGE, - number=6, - oneof='blueprint', - message='TerraformBlueprint', - ) - name: str = proto.Field( - proto.STRING, - number=1, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - labels: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=3, - ) - state: State = proto.Field( - proto.ENUM, - number=4, - enum=State, - ) - deployment: str = proto.Field( - proto.STRING, - number=5, - ) - preview_mode: PreviewMode = proto.Field( - proto.ENUM, - number=15, - enum=PreviewMode, - ) - service_account: str = proto.Field( - proto.STRING, - number=7, - ) - artifacts_gcs_bucket: str = proto.Field( - proto.STRING, - number=8, - optional=True, - ) - worker_pool: str = proto.Field( - proto.STRING, - number=9, - optional=True, - ) - error_code: ErrorCode = proto.Field( - proto.ENUM, - number=10, - enum=ErrorCode, - ) - error_status: status_pb2.Status = proto.Field( - proto.MESSAGE, - number=11, - message=status_pb2.Status, - ) - build: str = proto.Field( - proto.STRING, - number=12, - ) - tf_errors: MutableSequence['TerraformError'] = proto.RepeatedField( - proto.MESSAGE, - number=13, - message='TerraformError', - ) - error_logs: str = proto.Field( - proto.STRING, - number=14, - ) - preview_artifacts: 'PreviewArtifacts' = proto.Field( - proto.MESSAGE, - number=16, - message='PreviewArtifacts', - ) - logs: str = proto.Field( - proto.STRING, - number=17, - ) - tf_version: str = proto.Field( - proto.STRING, - number=18, - ) - tf_version_constraint: str = proto.Field( - proto.STRING, - number=19, - optional=True, - ) - annotations: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=20, - ) - provider_config: 'ProviderConfig' = proto.Field( - proto.MESSAGE, - number=21, - message='ProviderConfig', - ) - - -class PreviewOperationMetadata(proto.Message): - r"""Ephemeral metadata content describing the state of a preview - operation. - - Attributes: - step (google.cloud.config_v1.types.PreviewOperationMetadata.PreviewStep): - The current step the preview operation is - running. - preview_artifacts (google.cloud.config_v1.types.PreviewArtifacts): - Artifacts from preview. - logs (str): - Output only. Location of preview logs in - ``gs://{bucket}/{object}`` format. - build (str): - Output only. Cloud Build instance UUID - associated with this preview. - """ - class PreviewStep(proto.Enum): - r"""The possible steps a preview may be running. - - Values: - PREVIEW_STEP_UNSPECIFIED (0): - Unspecified preview step. - PREPARING_STORAGE_BUCKET (1): - Infra Manager is creating a Google Cloud - Storage bucket to store artifacts and metadata - about the preview. - DOWNLOADING_BLUEPRINT (2): - Downloading the blueprint onto the Google - Cloud Storage bucket. - RUNNING_TF_INIT (3): - Initializing Terraform using ``terraform init``. - RUNNING_TF_PLAN (4): - Running ``terraform plan``. - FETCHING_DEPLOYMENT (5): - Fetching a deployment. - LOCKING_DEPLOYMENT (6): - Locking a deployment. - UNLOCKING_DEPLOYMENT (7): - Unlocking a deployment. - SUCCEEDED (8): - Operation was successful. - FAILED (9): - Operation failed. - VALIDATING_REPOSITORY (10): - Validating the provided repository. - """ - PREVIEW_STEP_UNSPECIFIED = 0 - PREPARING_STORAGE_BUCKET = 1 - DOWNLOADING_BLUEPRINT = 2 - RUNNING_TF_INIT = 3 - RUNNING_TF_PLAN = 4 - FETCHING_DEPLOYMENT = 5 - LOCKING_DEPLOYMENT = 6 - UNLOCKING_DEPLOYMENT = 7 - SUCCEEDED = 8 - FAILED = 9 - VALIDATING_REPOSITORY = 10 - - step: PreviewStep = proto.Field( - proto.ENUM, - number=1, - enum=PreviewStep, - ) - preview_artifacts: 'PreviewArtifacts' = proto.Field( - proto.MESSAGE, - number=2, - message='PreviewArtifacts', - ) - logs: str = proto.Field( - proto.STRING, - number=3, - ) - build: str = proto.Field( - proto.STRING, - number=4, - ) - - -class PreviewArtifacts(proto.Message): - r"""Artifacts created by preview. - - Attributes: - content (str): - Output only. Location of a blueprint copy and other content - in Google Cloud Storage. Format: ``gs://{bucket}/{object}`` - artifacts (str): - Output only. Location of artifacts in Google Cloud Storage. - Format: ``gs://{bucket}/{object}`` - """ - - content: str = proto.Field( - proto.STRING, - number=1, - ) - artifacts: str = proto.Field( - proto.STRING, - number=2, - ) - - -class CreatePreviewRequest(proto.Message): - r"""A request to create a preview. - - Attributes: - parent (str): - Required. The parent in whose context the Preview is - created. The parent value is in the format: - 'projects/{project_id}/locations/{location}'. - preview_id (str): - Optional. The preview ID. - preview (google.cloud.config_v1.types.Preview): - Required. [Preview][google.cloud.config.v1.Preview] 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 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, - ) - preview_id: str = proto.Field( - proto.STRING, - number=2, - ) - preview: 'Preview' = proto.Field( - proto.MESSAGE, - number=3, - message='Preview', - ) - request_id: str = proto.Field( - proto.STRING, - number=4, - ) - - -class GetPreviewRequest(proto.Message): - r"""A request to get details about a preview. - - Attributes: - name (str): - Required. The name of the preview. Format: - 'projects/{project_id}/locations/{location}/previews/{preview}'. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListPreviewsRequest(proto.Message): - r"""A request to list all previews for a given project and - location. - - Attributes: - parent (str): - Required. The parent in whose context the Previews are - listed. The parent value is in the format: - 'projects/{project_id}/locations/{location}'. - page_size (int): - Optional. When requesting a page of resources, 'page_size' - specifies number of resources to return. If unspecified, at - most 500 will be returned. The maximum value is 1000. - page_token (str): - Optional. Token returned by previous call to - 'ListDeployments' which specifies the position - in the list from where to continue listing the - resources. - filter (str): - Optional. Lists the Deployments that match the filter - expression. A filter expression filters the resources listed - in the response. The expression must be of the form '{field} - {operator} {value}' where operators: '<', '>', '<=', '>=', - '!=', '=', ':' are supported (colon ':' represents a HAS - operator which is roughly synonymous with equality). {field} - can refer to a proto or JSON field, or a synthetic field. - Field names can be camelCase or snake_case. - - Examples: - - - Filter by name: name = - "projects/foo/locations/us-central1/deployments/bar - - - Filter by labels: - - - Resources that have a key called 'foo' labels.foo:\* - - Resources that have a key called 'foo' whose value is - 'bar' labels.foo = bar - - - Filter by state: - - - Deployments in CREATING state. state=CREATING - order_by (str): - Optional. Field to use to sort the list. - """ - - 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 ListPreviewsResponse(proto.Message): - r"""A response to a ``ListPreviews`` call. Contains a list of Previews. - - Attributes: - previews (MutableSequence[google.cloud.config_v1.types.Preview]): - List of [Previews][google.cloud.config.v1.Preview]. - next_page_token (str): - Token to be supplied to the next ListPreviews request via - ``page_token`` to obtain the next set of results. - unreachable (MutableSequence[str]): - Locations that could not be reached. - """ - - @property - def raw_page(self): - return self - - previews: MutableSequence['Preview'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Preview', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - unreachable: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - - -class DeletePreviewRequest(proto.Message): - r"""A request to delete a preview. - - Attributes: - name (str): - Required. The name of the Preview in the format: - 'projects/{project_id}/locations/{location}/previews/{preview}'. - 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 ExportPreviewResultRequest(proto.Message): - r"""A request to export preview results. - - Attributes: - parent (str): - Required. The preview whose results should be exported. The - preview value is in the format: - 'projects/{project_id}/locations/{location}/previews/{preview}'. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ExportPreviewResultResponse(proto.Message): - r"""A response to ``ExportPreviewResult`` call. Contains preview - results. - - Attributes: - result (google.cloud.config_v1.types.PreviewResult): - Output only. Signed URLs for accessing the - plan files. - """ - - result: 'PreviewResult' = proto.Field( - proto.MESSAGE, - number=1, - message='PreviewResult', - ) - - -class PreviewResult(proto.Message): - r"""Contains a signed Cloud Storage URLs. - - Attributes: - binary_signed_uri (str): - Output only. Plan binary signed URL - json_signed_uri (str): - Output only. Plan JSON signed URL - """ - - binary_signed_uri: str = proto.Field( - proto.STRING, - number=1, - ) - json_signed_uri: str = proto.Field( - proto.STRING, - number=2, - ) - - -class GetTerraformVersionRequest(proto.Message): - r"""The request message for the GetTerraformVersion method. - - Attributes: - name (str): - Required. The name of the TerraformVersion. Format: - 'projects/{project_id}/locations/{location}/terraformVersions/{terraform_version}' - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListTerraformVersionsRequest(proto.Message): - r"""The request message for the ListTerraformVersions method. - - Attributes: - parent (str): - Required. The parent in whose context the TerraformVersions - are listed. The parent value is in the format: - 'projects/{project_id}/locations/{location}'. - page_size (int): - Optional. When requesting a page of terraform versions, - 'page_size' specifies number of terraform versions to - return. If unspecified, at most 500 will be returned. The - maximum value is 1000. - page_token (str): - Optional. Token returned by previous call to - 'ListTerraformVersions' which specifies the - position in the list from where to continue - listing the terraform versions. - filter (str): - Optional. Lists the TerraformVersions that match the filter - expression. A filter expression filters the resources listed - in the response. The expression must be of the form '{field} - {operator} {value}' where operators: '<', '>', '<=', '>=', - '!=', '=', ':' are supported (colon ':' represents a HAS - operator which is roughly synonymous with equality). {field} - can refer to a proto or JSON field, or a synthetic field. - Field names can be camelCase or snake_case. - order_by (str): - Optional. Field to use to sort the list. - """ - - 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 ListTerraformVersionsResponse(proto.Message): - r"""The response message for the ``ListTerraformVersions`` method. - - Attributes: - terraform_versions (MutableSequence[google.cloud.config_v1.types.TerraformVersion]): - List of - [TerraformVersion][google.cloud.config.v1.TerraformVersion]s. - next_page_token (str): - Token to be supplied to the next ListTerraformVersions - request via ``page_token`` to obtain the next set of - results. - unreachable (MutableSequence[str]): - Unreachable resources, if any. - """ - - @property - def raw_page(self): - return self - - terraform_versions: MutableSequence['TerraformVersion'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='TerraformVersion', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - unreachable: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - - -class TerraformVersion(proto.Message): - r"""A TerraformVersion represents the support state the - corresponding Terraform version. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - name (str): - Identifier. The version name is in the format: - 'projects/{project_id}/locations/{location}/terraformVersions/{terraform_version}'. - state (google.cloud.config_v1.types.TerraformVersion.State): - Output only. The state of the version, - ACTIVE, DEPRECATED or OBSOLETE. - support_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. When the version is supported. - deprecate_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. When the version is deprecated. - - This field is a member of `oneof`_ ``_deprecate_time``. - obsolete_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. When the version is obsolete. - - This field is a member of `oneof`_ ``_obsolete_time``. - """ - class State(proto.Enum): - r"""Possible states of a TerraformVersion. - - Values: - STATE_UNSPECIFIED (0): - The default value. This value is used if the - state is omitted. - ACTIVE (1): - The version is actively supported. - DEPRECATED (2): - The version is deprecated. - OBSOLETE (3): - The version is obsolete. - """ - STATE_UNSPECIFIED = 0 - ACTIVE = 1 - DEPRECATED = 2 - OBSOLETE = 3 - - name: str = proto.Field( - proto.STRING, - number=1, - ) - state: State = proto.Field( - proto.ENUM, - number=2, - enum=State, - ) - support_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - deprecate_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=4, - optional=True, - message=timestamp_pb2.Timestamp, - ) - obsolete_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=5, - optional=True, - message=timestamp_pb2.Timestamp, - ) - - -class ResourceChangeTerraformInfo(proto.Message): - r"""Terraform info of a ResourceChange. - - Attributes: - address (str): - Output only. TF resource address that - uniquely identifies the resource. - type_ (str): - Output only. TF resource type. - resource_name (str): - Output only. TF resource name. - provider (str): - Output only. TF resource provider. - actions (MutableSequence[str]): - Output only. TF resource actions. - """ - - address: str = proto.Field( - proto.STRING, - number=1, - ) - type_: str = proto.Field( - proto.STRING, - number=2, - ) - resource_name: str = proto.Field( - proto.STRING, - number=3, - ) - provider: str = proto.Field( - proto.STRING, - number=4, - ) - actions: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=5, - ) - - -class ResourceChange(proto.Message): - r"""A resource change represents a change to a resource in the - state file. - - Attributes: - name (str): - Identifier. The name of the resource change. Format: - 'projects/{project_id}/locations/{location}/previews/{preview}/resourceChanges/{resource_change}'. - terraform_info (google.cloud.config_v1.types.ResourceChangeTerraformInfo): - Output only. Terraform info of the resource - change. - intent (google.cloud.config_v1.types.ResourceChange.Intent): - Output only. The intent of the resource - change. - property_changes (MutableSequence[google.cloud.config_v1.types.PropertyChange]): - Output only. The property changes of the - resource change. - """ - class Intent(proto.Enum): - r"""Possible intent of the resource change. - - Values: - INTENT_UNSPECIFIED (0): - The default value. - CREATE (1): - The resource will be created. - UPDATE (2): - The resource will be updated. - DELETE (3): - The resource will be deleted. - RECREATE (4): - The resource will be recreated. - UNCHANGED (5): - The resource will be untouched. - """ - INTENT_UNSPECIFIED = 0 - CREATE = 1 - UPDATE = 2 - DELETE = 3 - RECREATE = 4 - UNCHANGED = 5 - - name: str = proto.Field( - proto.STRING, - number=1, - ) - terraform_info: 'ResourceChangeTerraformInfo' = proto.Field( - proto.MESSAGE, - number=2, - message='ResourceChangeTerraformInfo', - ) - intent: Intent = proto.Field( - proto.ENUM, - number=3, - enum=Intent, - ) - property_changes: MutableSequence['PropertyChange'] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='PropertyChange', - ) - - -class PropertyChange(proto.Message): - r"""A property change represents a change to a property in the - state file. - - Attributes: - path (str): - Output only. The path of the property change. - before_sensitive_paths (MutableSequence[str]): - Output only. The paths of sensitive fields in ``before``. - Paths are relative to ``path``. - before (google.protobuf.struct_pb2.Value): - Output only. Representations of the object - value before the actions. - after_sensitive_paths (MutableSequence[str]): - Output only. The paths of sensitive fields in ``after``. - Paths are relative to ``path``. - after (google.protobuf.struct_pb2.Value): - Output only. Representations of the object - value after the actions. - """ - - path: str = proto.Field( - proto.STRING, - number=1, - ) - before_sensitive_paths: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=2, - ) - before: struct_pb2.Value = proto.Field( - proto.MESSAGE, - number=3, - message=struct_pb2.Value, - ) - after_sensitive_paths: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=4, - ) - after: struct_pb2.Value = proto.Field( - proto.MESSAGE, - number=5, - message=struct_pb2.Value, - ) - - -class ListResourceChangesRequest(proto.Message): - r"""The request message for the ListResourceChanges method. - - Attributes: - parent (str): - Required. The parent in whose context the ResourceChanges - are listed. The parent value is in the format: - 'projects/{project_id}/locations/{location}/previews/{preview}'. - page_size (int): - Optional. When requesting a page of resource changes, - 'page_size' specifies number of resource changes to return. - If unspecified, at most 500 will be returned. The maximum - value is 1000. - page_token (str): - Optional. Token returned by previous call to - 'ListResourceChanges' which specifies the - position in the list from where to continue - listing the resource changes. - filter (str): - Optional. Lists the resource changes that match the filter - expression. A filter expression filters the resource changes - listed in the response. The expression must be of the form - '{field} {operator} {value}' where operators: '<', '>', - '<=', '>=', '!=', '=', ':' are supported (colon ':' - represents a HAS operator which is roughly synonymous with - equality). {field} can refer to a proto or JSON field, or a - synthetic field. Field names can be camelCase or snake_case. - - Examples: - - - Filter by name: name = - "projects/foo/locations/us-central1/previews/dep/resourceChanges/baz - order_by (str): - Optional. Field to use to sort the list. - """ - - 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 ListResourceChangesResponse(proto.Message): - r"""A response to a 'ListResourceChanges' call. Contains a list - of ResourceChanges. - - Attributes: - resource_changes (MutableSequence[google.cloud.config_v1.types.ResourceChange]): - List of ResourceChanges. - next_page_token (str): - A token to request the next page of resources - from the 'ListResourceChanges' method. The value - of an empty string means that there are no more - resources to return. - unreachable (MutableSequence[str]): - Unreachable resources, if any. - """ - - @property - def raw_page(self): - return self - - resource_changes: MutableSequence['ResourceChange'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='ResourceChange', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - unreachable: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - - -class GetResourceChangeRequest(proto.Message): - r"""The request message for the GetResourceChange method. - - Attributes: - name (str): - Required. The name of the resource change to retrieve. - Format: - 'projects/{project_id}/locations/{location}/previews/{preview}/resourceChanges/{resource_change}'. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ResourceDriftTerraformInfo(proto.Message): - r"""Terraform info of a ResourceChange. - - Attributes: - address (str): - Output only. The address of the drifted - resource. - type_ (str): - Output only. The type of the drifted - resource. - resource_name (str): - Output only. TF resource name. - provider (str): - Output only. The provider of the drifted - resource. - """ - - address: str = proto.Field( - proto.STRING, - number=1, - ) - type_: str = proto.Field( - proto.STRING, - number=2, - ) - resource_name: str = proto.Field( - proto.STRING, - number=3, - ) - provider: str = proto.Field( - proto.STRING, - number=4, - ) - - -class ResourceDrift(proto.Message): - r"""A resource drift represents a drift to a resource in the - state file. - - Attributes: - name (str): - Identifier. The name of the resource drift. Format: - 'projects/{project_id}/locations/{location}/previews/{preview}/resourceDrifts/{resource_drift}'. - terraform_info (google.cloud.config_v1.types.ResourceDriftTerraformInfo): - Output only. Terraform info of the resource - drift. - property_drifts (MutableSequence[google.cloud.config_v1.types.PropertyDrift]): - Output only. The property drifts of the - resource drift. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - terraform_info: 'ResourceDriftTerraformInfo' = proto.Field( - proto.MESSAGE, - number=2, - message='ResourceDriftTerraformInfo', - ) - property_drifts: MutableSequence['PropertyDrift'] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='PropertyDrift', - ) - - -class PropertyDrift(proto.Message): - r"""A property drift represents a drift to a property in the - state file. - - Attributes: - path (str): - Output only. The path of the property drift. - before_sensitive_paths (MutableSequence[str]): - Output only. The paths of sensitive fields in ``before``. - Paths are relative to ``path``. - before (google.protobuf.struct_pb2.Value): - Output only. Representations of the object - value before the actions. - after_sensitive_paths (MutableSequence[str]): - Output only. The paths of sensitive fields in ``after``. - Paths are relative to ``path``. - after (google.protobuf.struct_pb2.Value): - Output only. Representations of the object - value after the actions. - """ - - path: str = proto.Field( - proto.STRING, - number=1, - ) - before_sensitive_paths: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=2, - ) - before: struct_pb2.Value = proto.Field( - proto.MESSAGE, - number=3, - message=struct_pb2.Value, - ) - after_sensitive_paths: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=4, - ) - after: struct_pb2.Value = proto.Field( - proto.MESSAGE, - number=5, - message=struct_pb2.Value, - ) - - -class ListResourceDriftsRequest(proto.Message): - r"""The request message for the ListResourceDrifts method. - - Attributes: - parent (str): - Required. The parent in whose context the ResourceDrifts are - listed. The parent value is in the format: - 'projects/{project_id}/locations/{location}/previews/{preview}'. - page_size (int): - Optional. When requesting a page of resource drifts, - 'page_size' specifies number of resource drifts to return. - If unspecified, at most 500 will be returned. The maximum - value is 1000. - page_token (str): - Optional. Token returned by previous call to - 'ListResourceDrifts' which specifies the - position in the list from where to continue - listing the resource drifts. - filter (str): - Optional. Lists the resource drifts that match the filter - expression. A filter expression filters the resource drifts - listed in the response. The expression must be of the form - '{field} {operator} {value}' where operators: '<', '>', - '<=', '>=', '!=', '=', ':' are supported (colon ':' - represents a HAS operator which is roughly synonymous with - equality). {field} can refer to a proto or JSON field, or a - synthetic field. Field names can be camelCase or snake_case. - - Examples: - - - Filter by name: name = - "projects/foo/locations/us-central1/previews/dep/resourceDrifts/baz - order_by (str): - Optional. Field to use to sort the list. - """ - - 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 ListResourceDriftsResponse(proto.Message): - r"""A response to a 'ListResourceDrifts' call. Contains a list of - ResourceDrifts. - - Attributes: - resource_drifts (MutableSequence[google.cloud.config_v1.types.ResourceDrift]): - List of ResourceDrifts. - next_page_token (str): - A token to request the next page of resources - from the 'ListResourceDrifts' method. The value - of an empty string means that there are no more - resources to return. - unreachable (MutableSequence[str]): - Unreachable resources, if any. - """ - - @property - def raw_page(self): - return self - - resource_drifts: MutableSequence['ResourceDrift'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='ResourceDrift', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - unreachable: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - - -class GetResourceDriftRequest(proto.Message): - r"""The request message for the GetResourceDrift method. - - Attributes: - name (str): - Required. The name of the resource drift to retrieve. - Format: - 'projects/{project_id}/locations/{location}/previews/{preview}/resourceDrifts/{resource_drift}'. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ProviderConfig(proto.Message): - r"""ProviderConfig contains the provider configurations. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - source_type (google.cloud.config_v1.types.ProviderConfig.ProviderSource): - Optional. ProviderSource specifies the source - type of the provider. - - This field is a member of `oneof`_ ``_source_type``. - """ - class ProviderSource(proto.Enum): - r"""ProviderSource represents the source type of the provider. - - Values: - PROVIDER_SOURCE_UNSPECIFIED (0): - Unspecified source type, default to public - sources. - SERVICE_MAINTAINED (1): - Service maintained provider source type. - """ - PROVIDER_SOURCE_UNSPECIFIED = 0 - SERVICE_MAINTAINED = 1 - - source_type: ProviderSource = proto.Field( - proto.ENUM, - number=1, - optional=True, - enum=ProviderSource, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-config/v1/mypy.ini b/owl-bot-staging/google-cloud-config/v1/mypy.ini deleted file mode 100644 index 574c5aed394b..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.7 -namespace_packages = True diff --git a/owl-bot-staging/google-cloud-config/v1/noxfile.py b/owl-bot-staging/google-cloud-config/v1/noxfile.py deleted file mode 100644 index bd3a52533ecd..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/noxfile.py +++ /dev/null @@ -1,591 +0,0 @@ -# -*- 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. -# -import os -import pathlib -import re -import shutil - -from typing import Dict, List -import warnings - -import nox - -BLACK_VERSION = "black[jupyter]==23.7.0" -ISORT_VERSION = "isort==5.11.0" - -LINT_PATHS = ["docs", "google", "tests", "noxfile.py", "setup.py"] - -ALL_PYTHON = [ - "3.7", - "3.8", - "3.9", - "3.10", - "3.11", - "3.12", - "3.13", -] - -DEFAULT_PYTHON_VERSION = ALL_PYTHON[-1] - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = "google-cloud-config" - -UNIT_TEST_STANDARD_DEPENDENCIES = [ - "mock", - "asyncmock", - "pytest", - "pytest-cov", - "pytest-asyncio", -] -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_BY_PYTHON: Dict[str, List[str]] = {} - -SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ["3.8", "3.9", "3.10", "3.11", "3.12", "3.13"] -SYSTEM_TEST_STANDARD_DEPENDENCIES = [ - "mock", - "pytest", - "google-cloud-testutils", -] -SYSTEM_TEST_EXTERNAL_DEPENDENCIES: List[str] = [] -SYSTEM_TEST_LOCAL_DEPENDENCIES: List[str] = [] -SYSTEM_TEST_DEPENDENCIES: List[str] = [] -SYSTEM_TEST_EXTRAS: List[str] = [] -SYSTEM_TEST_EXTRAS_BY_PYTHON: Dict[str, List[str]] = {} - -nox.options.sessions = [ - "unit", - "system", - "cover", - "lint", - "lint_setup_py", - "blacken", - "docs", -] - -# Error if a python version is missing -nox.options.error_on_missing_interpreters = True - - -@nox.session(python=ALL_PYTHON) -def mypy(session): - """Run the type checker.""" - session.install( - # TODO(https://github.com/googleapis/gapic-generator-python/issues/2410): Use the latest version of mypy - "mypy<1.16.0", - "types-requests", - "types-protobuf", - ) - session.install(".") - session.run( - "mypy", - "-p", - "google", - ) - - -@nox.session -def update_lower_bounds(session): - """Update lower bounds in constraints.txt to match setup.py""" - session.install("google-cloud-testutils") - session.install(".") - - session.run( - "lower-bound-checker", - "update", - "--package-name", - PACKAGE_NAME, - "--constraints-file", - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - - -@nox.session -def check_lower_bounds(session): - """Check lower bounds in setup.py are reflected in constraints file""" - session.install("google-cloud-testutils") - session.install(".") - - session.run( - "lower-bound-checker", - "check", - "--package-name", - PACKAGE_NAME, - "--constraints-file", - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def lint(session): - """Run linters. - - Returns a failure if the linters find linting errors or sufficiently - serious code quality issues. - """ - session.install("flake8", BLACK_VERSION) - session.run( - "black", - "--check", - *LINT_PATHS, - ) - - session.run("flake8", "google", "tests") - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def blacken(session): - """Run black. Format code to uniform standard.""" - session.install(BLACK_VERSION) - session.run( - "black", - *LINT_PATHS, - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def format(session): - """ - Run isort to sort imports. Then run black - to format code to uniform standard. - """ - session.install(BLACK_VERSION, ISORT_VERSION) - # Use the --fss option to sort imports using strict alphabetical order. - # See https://pycqa.github.io/isort/docs/configuration/options.html#force-sort-within-sections - session.run( - "isort", - "--fss", - *LINT_PATHS, - ) - session.run( - "black", - *LINT_PATHS, - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def lint_setup_py(session): - """Verify that setup.py is valid (including RST check).""" - session.install("setuptools", "docutils", "pygments") - session.run("python", "setup.py", "check", "--restructuredtext", "--strict") - - -def install_unittest_dependencies(session, *constraints): - standard_deps = UNIT_TEST_STANDARD_DEPENDENCIES + UNIT_TEST_DEPENDENCIES - session.install(*standard_deps, *constraints) - - if UNIT_TEST_EXTERNAL_DEPENDENCIES: - warnings.warn( - "'unit_test_external_dependencies' is deprecated. Instead, please " - "use 'unit_test_dependencies' or 'unit_test_local_dependencies'.", - DeprecationWarning, - ) - session.install(*UNIT_TEST_EXTERNAL_DEPENDENCIES, *constraints) - - if UNIT_TEST_LOCAL_DEPENDENCIES: - session.install(*UNIT_TEST_LOCAL_DEPENDENCIES, *constraints) - - if UNIT_TEST_EXTRAS_BY_PYTHON: - extras = UNIT_TEST_EXTRAS_BY_PYTHON.get(session.python, []) - elif UNIT_TEST_EXTRAS: - extras = UNIT_TEST_EXTRAS - else: - extras = [] - - if extras: - session.install("-e", f".[{','.join(extras)}]", *constraints) - else: - session.install("-e", ".", *constraints) - - -@nox.session(python=ALL_PYTHON) -@nox.parametrize( - "protobuf_implementation", - ["python", "upb", "cpp"], -) -def unit(session, protobuf_implementation): - # Install all test dependencies, then install this package in-place. - - if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"): - session.skip("cpp implementation is not supported in python 3.11+") - - constraints_path = str( - CURRENT_DIRECTORY / "testing" / f"constraints-{session.python}.txt" - ) - install_unittest_dependencies(session, "-c", constraints_path) - - # TODO(https://github.com/googleapis/synthtool/issues/1976): - # Remove the 'cpp' implementation once support for Protobuf 3.x is dropped. - # The 'cpp' implementation requires Protobuf<4. - if protobuf_implementation == "cpp": - session.install("protobuf<4") - - # Run py.test against the unit tests. - session.run( - "py.test", - "--quiet", - f"--junitxml=unit_{session.python}_sponge_log.xml", - "--cov=google", - "--cov=tests/unit", - "--cov-append", - "--cov-config=.coveragerc", - "--cov-report=", - "--cov-fail-under=0", - os.path.join("tests", "unit"), - *session.posargs, - env={ - "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, - }, - ) - - -def install_systemtest_dependencies(session, *constraints): - session.install("--pre", "grpcio") - - session.install(*SYSTEM_TEST_STANDARD_DEPENDENCIES, *constraints) - - if SYSTEM_TEST_EXTERNAL_DEPENDENCIES: - session.install(*SYSTEM_TEST_EXTERNAL_DEPENDENCIES, *constraints) - - if SYSTEM_TEST_LOCAL_DEPENDENCIES: - session.install("-e", *SYSTEM_TEST_LOCAL_DEPENDENCIES, *constraints) - - if SYSTEM_TEST_DEPENDENCIES: - session.install("-e", *SYSTEM_TEST_DEPENDENCIES, *constraints) - - if SYSTEM_TEST_EXTRAS_BY_PYTHON: - extras = SYSTEM_TEST_EXTRAS_BY_PYTHON.get(session.python, []) - elif SYSTEM_TEST_EXTRAS: - extras = SYSTEM_TEST_EXTRAS - else: - extras = [] - - if extras: - session.install("-e", f".[{','.join(extras)}]", *constraints) - else: - session.install("-e", ".", *constraints) - - -@nox.session(python=SYSTEM_TEST_PYTHON_VERSIONS) -def system(session): - """Run the system test suite.""" - constraints_path = str( - CURRENT_DIRECTORY / "testing" / f"constraints-{session.python}.txt" - ) - system_test_path = os.path.join("tests", "system.py") - system_test_folder_path = os.path.join("tests", "system") - - # Check the value of `RUN_SYSTEM_TESTS` env var. It defaults to true. - if os.environ.get("RUN_SYSTEM_TESTS", "true") == "false": - session.skip("RUN_SYSTEM_TESTS is set to false, skipping") - # Install pyopenssl for mTLS testing. - if os.environ.get("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") == "true": - session.install("pyopenssl") - - system_test_exists = os.path.exists(system_test_path) - system_test_folder_exists = os.path.exists(system_test_folder_path) - # Sanity check: only run tests if found. - if not system_test_exists and not system_test_folder_exists: - session.skip("System tests were not found") - - install_systemtest_dependencies(session, "-c", constraints_path) - - # Run py.test against the system tests. - if system_test_exists: - session.run( - "py.test", - "--quiet", - f"--junitxml=system_{session.python}_sponge_log.xml", - system_test_path, - *session.posargs, - ) - if system_test_folder_exists: - session.run( - "py.test", - "--quiet", - f"--junitxml=system_{session.python}_sponge_log.xml", - system_test_folder_path, - *session.posargs, - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def cover(session): - """Run the final coverage report. - - This outputs the coverage report aggregating coverage from the unit - test runs (not system test runs), and then erases coverage data. - """ - session.install("coverage", "pytest-cov") - session.run("coverage", "report", "--show-missing", "--fail-under=100") - - session.run("coverage", "erase") - - -@nox.session(python="3.10") -def docs(session): - """Build the docs for this library.""" - - session.install("-e", ".") - session.install( - # We need to pin to specific versions of the `sphinxcontrib-*` packages - # which still support sphinx 4.x. - # See https://github.com/googleapis/sphinx-docfx-yaml/issues/344 - # and https://github.com/googleapis/sphinx-docfx-yaml/issues/345. - "sphinxcontrib-applehelp==1.0.4", - "sphinxcontrib-devhelp==1.0.2", - "sphinxcontrib-htmlhelp==2.0.1", - "sphinxcontrib-qthelp==1.0.3", - "sphinxcontrib-serializinghtml==1.1.5", - "sphinx==4.5.0", - "alabaster", - "recommonmark", - ) - - shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) - session.run( - "sphinx-build", - "-W", # warnings as errors - "-T", # show full traceback on exception - "-N", # no colors - "-b", "html", # builder - "-d", os.path.join("docs", "_build", "doctrees", ""), # cache directory - # paths to build: - os.path.join("docs", ""), - os.path.join("docs", "_build", "html", ""), - ) - - -@nox.session(python="3.10") -def docfx(session): - """Build the docfx yaml files for this library.""" - - session.install("-e", ".") - session.install( - # We need to pin to specific versions of the `sphinxcontrib-*` packages - # which still support sphinx 4.x. - # See https://github.com/googleapis/sphinx-docfx-yaml/issues/344 - # and https://github.com/googleapis/sphinx-docfx-yaml/issues/345. - "sphinxcontrib-applehelp==1.0.4", - "sphinxcontrib-devhelp==1.0.2", - "sphinxcontrib-htmlhelp==2.0.1", - "sphinxcontrib-qthelp==1.0.3", - "sphinxcontrib-serializinghtml==1.1.5", - "gcp-sphinx-docfx-yaml", - "alabaster", - "recommonmark", - ) - - shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) - session.run( - "sphinx-build", - "-T", # show full traceback on exception - "-N", # no colors - "-D", - ( - "extensions=sphinx.ext.autodoc," - "sphinx.ext.autosummary," - "docfx_yaml.extension," - "sphinx.ext.intersphinx," - "sphinx.ext.coverage," - "sphinx.ext.napoleon," - "sphinx.ext.todo," - "sphinx.ext.viewcode," - "recommonmark" - ), - "-b", - "html", - "-d", - os.path.join("docs", "_build", "doctrees", ""), - os.path.join("docs", ""), - os.path.join("docs", "_build", "html", ""), - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -@nox.parametrize( - "protobuf_implementation", - ["python", "upb", "cpp"], -) -def prerelease_deps(session, protobuf_implementation): - """ - Run all tests with pre-release versions of dependencies installed - rather than the standard non pre-release versions. - Pre-release versions can be installed using - `pip install --pre `. - """ - - if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"): - session.skip("cpp implementation is not supported in python 3.11+") - - # Install all dependencies - session.install("-e", ".") - - # Install dependencies for the unit test environment - unit_deps_all = UNIT_TEST_STANDARD_DEPENDENCIES + UNIT_TEST_EXTERNAL_DEPENDENCIES - session.install(*unit_deps_all) - - # Install dependencies for the system test environment - system_deps_all = ( - SYSTEM_TEST_STANDARD_DEPENDENCIES - + SYSTEM_TEST_EXTERNAL_DEPENDENCIES - + SYSTEM_TEST_EXTRAS - ) - session.install(*system_deps_all) - - # Because we test minimum dependency versions on the minimum Python - # version, the first version we test with in the unit tests sessions has a - # constraints file containing all dependencies and extras. - with open( - CURRENT_DIRECTORY / "testing" / f"constraints-{ALL_PYTHON[0]}.txt", - encoding="utf-8", - ) as constraints_file: - constraints_text = constraints_file.read() - - # Ignore leading whitespace and comment lines. - constraints_deps = [ - match.group(1) - for match in re.finditer( - r"^\s*(\S+)(?===\S+)", constraints_text, flags=re.MULTILINE - ) - ] - - # Install dependencies specified in `testing/constraints-X.txt`. - session.install(*constraints_deps) - - # Note: If a dependency is added to the `prerel_deps` list, - # the `core_dependencies_from_source` list in the `core_deps_from_source` - # nox session should also be updated. - prerel_deps = [ - "googleapis-common-protos", - "google-api-core", - "google-auth", - "grpc-google-iam-v1", - "grpcio", - "grpcio-status", - "protobuf", - "proto-plus", - ] - - for dep in prerel_deps: - session.install("--pre", "--no-deps", "--ignore-installed", dep) - # TODO(https://github.com/grpc/grpc/issues/38965): Add `grpcio-status`` - # to the dictionary below once this bug is fixed. - # TODO(https://github.com/googleapis/google-cloud-python/issues/13643): Add - # `googleapis-common-protos` and `grpc-google-iam-v1` to the dictionary below - # once this bug is fixed. - package_namespaces = { - "google-api-core": "google.api_core", - "google-auth": "google.auth", - "grpcio": "grpc", - "protobuf": "google.protobuf", - "proto-plus": "proto", - } - - version_namespace = package_namespaces.get(dep) - - print(f"Installed {dep}") - if version_namespace: - session.run( - "python", - "-c", - f"import {version_namespace}; print({version_namespace}.__version__)", - ) - - session.run( - "py.test", - "tests/unit", - env={ - "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, - }, - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -@nox.parametrize( - "protobuf_implementation", - ["python", "upb"], -) -def core_deps_from_source(session, protobuf_implementation): - """Run all tests with core dependencies installed from source - rather than pulling the dependencies from PyPI. - """ - - # Install all dependencies - session.install("-e", ".") - - # Install dependencies for the unit test environment - unit_deps_all = UNIT_TEST_STANDARD_DEPENDENCIES + UNIT_TEST_EXTERNAL_DEPENDENCIES - session.install(*unit_deps_all) - - # Install dependencies for the system test environment - system_deps_all = ( - SYSTEM_TEST_STANDARD_DEPENDENCIES - + SYSTEM_TEST_EXTERNAL_DEPENDENCIES - + SYSTEM_TEST_EXTRAS - ) - session.install(*system_deps_all) - - # Because we test minimum dependency versions on the minimum Python - # version, the first version we test with in the unit tests sessions has a - # constraints file containing all dependencies and extras. - with open( - CURRENT_DIRECTORY / "testing" / f"constraints-{ALL_PYTHON[0]}.txt", - encoding="utf-8", - ) as constraints_file: - constraints_text = constraints_file.read() - - # Ignore leading whitespace and comment lines. - constraints_deps = [ - match.group(1) - for match in re.finditer( - r"^\s*(\S+)(?===\S+)", constraints_text, flags=re.MULTILINE - ) - ] - - # Install dependencies specified in `testing/constraints-X.txt`. - session.install(*constraints_deps) - - # TODO(https://github.com/googleapis/gapic-generator-python/issues/2358): `grpcio` and - # `grpcio-status` should be added to the list below so that they are installed from source, - # rather than PyPI. - # TODO(https://github.com/googleapis/gapic-generator-python/issues/2357): `protobuf` should be - # added to the list below so that it is installed from source, rather than PyPI - # Note: If a dependency is added to the `core_dependencies_from_source` list, - # the `prerel_deps` list in the `prerelease_deps` nox session should also be updated. - core_dependencies_from_source = [ - "googleapis-common-protos @ git+https://github.com/googleapis/google-cloud-python#egg=googleapis-common-protos&subdirectory=packages/googleapis-common-protos", - "google-api-core @ git+https://github.com/googleapis/python-api-core.git", - "google-auth @ git+https://github.com/googleapis/google-auth-library-python.git", - "grpc-google-iam-v1 @ git+https://github.com/googleapis/google-cloud-python#egg=grpc-google-iam-v1&subdirectory=packages/grpc-google-iam-v1", - "proto-plus @ git+https://github.com/googleapis/proto-plus-python.git", - ] - - for dep in core_dependencies_from_source: - session.install(dep, "--no-deps", "--ignore-installed") - print(f"Installed {dep}") - - session.run( - "py.test", - "tests/unit", - env={ - "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, - }, - ) diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_create_deployment_async.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_create_deployment_async.py deleted file mode 100644 index 3fd5e2cc479c..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_create_deployment_async.py +++ /dev/null @@ -1,61 +0,0 @@ -# -*- 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 code. DO NOT EDIT! -# -# Snippet for CreateDeployment -# 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-config - - -# [START config_v1_generated_Config_CreateDeployment_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 config_v1 - - -async def sample_create_deployment(): - # Create a client - client = config_v1.ConfigAsyncClient() - - # Initialize request argument(s) - deployment = config_v1.Deployment() - deployment.terraform_blueprint.gcs_source = "gcs_source_value" - - request = config_v1.CreateDeploymentRequest( - parent="parent_value", - deployment_id="deployment_id_value", - deployment=deployment, - ) - - # Make the request - operation = client.create_deployment(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END config_v1_generated_Config_CreateDeployment_async] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_create_deployment_sync.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_create_deployment_sync.py deleted file mode 100644 index 13e926d69c3c..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_create_deployment_sync.py +++ /dev/null @@ -1,61 +0,0 @@ -# -*- 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 code. DO NOT EDIT! -# -# Snippet for CreateDeployment -# 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-config - - -# [START config_v1_generated_Config_CreateDeployment_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 config_v1 - - -def sample_create_deployment(): - # Create a client - client = config_v1.ConfigClient() - - # Initialize request argument(s) - deployment = config_v1.Deployment() - deployment.terraform_blueprint.gcs_source = "gcs_source_value" - - request = config_v1.CreateDeploymentRequest( - parent="parent_value", - deployment_id="deployment_id_value", - deployment=deployment, - ) - - # Make the request - operation = client.create_deployment(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END config_v1_generated_Config_CreateDeployment_sync] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_create_preview_async.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_create_preview_async.py deleted file mode 100644 index ae0f1c8ad737..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_create_preview_async.py +++ /dev/null @@ -1,61 +0,0 @@ -# -*- 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 code. DO NOT EDIT! -# -# Snippet for CreatePreview -# 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-config - - -# [START config_v1_generated_Config_CreatePreview_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 config_v1 - - -async def sample_create_preview(): - # Create a client - client = config_v1.ConfigAsyncClient() - - # Initialize request argument(s) - preview = config_v1.Preview() - preview.terraform_blueprint.gcs_source = "gcs_source_value" - preview.service_account = "service_account_value" - - request = config_v1.CreatePreviewRequest( - parent="parent_value", - preview=preview, - ) - - # Make the request - operation = client.create_preview(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END config_v1_generated_Config_CreatePreview_async] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_create_preview_sync.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_create_preview_sync.py deleted file mode 100644 index 6a8d6dd8af26..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_create_preview_sync.py +++ /dev/null @@ -1,61 +0,0 @@ -# -*- 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 code. DO NOT EDIT! -# -# Snippet for CreatePreview -# 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-config - - -# [START config_v1_generated_Config_CreatePreview_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 config_v1 - - -def sample_create_preview(): - # Create a client - client = config_v1.ConfigClient() - - # Initialize request argument(s) - preview = config_v1.Preview() - preview.terraform_blueprint.gcs_source = "gcs_source_value" - preview.service_account = "service_account_value" - - request = config_v1.CreatePreviewRequest( - parent="parent_value", - preview=preview, - ) - - # Make the request - operation = client.create_preview(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END config_v1_generated_Config_CreatePreview_sync] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_delete_deployment_async.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_delete_deployment_async.py deleted file mode 100644 index 13302b22c1ab..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_delete_deployment_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- 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 code. DO NOT EDIT! -# -# Snippet for DeleteDeployment -# 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-config - - -# [START config_v1_generated_Config_DeleteDeployment_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 config_v1 - - -async def sample_delete_deployment(): - # Create a client - client = config_v1.ConfigAsyncClient() - - # Initialize request argument(s) - request = config_v1.DeleteDeploymentRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_deployment(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END config_v1_generated_Config_DeleteDeployment_async] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_delete_deployment_sync.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_delete_deployment_sync.py deleted file mode 100644 index 5c3461d83d46..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_delete_deployment_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- 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 code. DO NOT EDIT! -# -# Snippet for DeleteDeployment -# 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-config - - -# [START config_v1_generated_Config_DeleteDeployment_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 config_v1 - - -def sample_delete_deployment(): - # Create a client - client = config_v1.ConfigClient() - - # Initialize request argument(s) - request = config_v1.DeleteDeploymentRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_deployment(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END config_v1_generated_Config_DeleteDeployment_sync] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_delete_preview_async.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_delete_preview_async.py deleted file mode 100644 index 1df8aae40d9e..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_delete_preview_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- 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 code. DO NOT EDIT! -# -# Snippet for DeletePreview -# 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-config - - -# [START config_v1_generated_Config_DeletePreview_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 config_v1 - - -async def sample_delete_preview(): - # Create a client - client = config_v1.ConfigAsyncClient() - - # Initialize request argument(s) - request = config_v1.DeletePreviewRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_preview(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END config_v1_generated_Config_DeletePreview_async] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_delete_preview_sync.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_delete_preview_sync.py deleted file mode 100644 index fde6f6cddcb1..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_delete_preview_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- 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 code. DO NOT EDIT! -# -# Snippet for DeletePreview -# 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-config - - -# [START config_v1_generated_Config_DeletePreview_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 config_v1 - - -def sample_delete_preview(): - # Create a client - client = config_v1.ConfigClient() - - # Initialize request argument(s) - request = config_v1.DeletePreviewRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_preview(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END config_v1_generated_Config_DeletePreview_sync] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_delete_statefile_async.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_delete_statefile_async.py deleted file mode 100644 index fdfd574f8b60..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_delete_statefile_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- 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 code. DO NOT EDIT! -# -# Snippet for DeleteStatefile -# 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-config - - -# [START config_v1_generated_Config_DeleteStatefile_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 config_v1 - - -async def sample_delete_statefile(): - # Create a client - client = config_v1.ConfigAsyncClient() - - # Initialize request argument(s) - request = config_v1.DeleteStatefileRequest( - name="name_value", - lock_id=725, - ) - - # Make the request - await client.delete_statefile(request=request) - - -# [END config_v1_generated_Config_DeleteStatefile_async] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_delete_statefile_sync.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_delete_statefile_sync.py deleted file mode 100644 index c2c686592a1a..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_delete_statefile_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- 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 code. DO NOT EDIT! -# -# Snippet for DeleteStatefile -# 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-config - - -# [START config_v1_generated_Config_DeleteStatefile_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 config_v1 - - -def sample_delete_statefile(): - # Create a client - client = config_v1.ConfigClient() - - # Initialize request argument(s) - request = config_v1.DeleteStatefileRequest( - name="name_value", - lock_id=725, - ) - - # Make the request - client.delete_statefile(request=request) - - -# [END config_v1_generated_Config_DeleteStatefile_sync] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_export_deployment_statefile_async.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_export_deployment_statefile_async.py deleted file mode 100644 index d602d58d6c51..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_export_deployment_statefile_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- 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 code. DO NOT EDIT! -# -# Snippet for ExportDeploymentStatefile -# 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-config - - -# [START config_v1_generated_Config_ExportDeploymentStatefile_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 config_v1 - - -async def sample_export_deployment_statefile(): - # Create a client - client = config_v1.ConfigAsyncClient() - - # Initialize request argument(s) - request = config_v1.ExportDeploymentStatefileRequest( - parent="parent_value", - ) - - # Make the request - response = await client.export_deployment_statefile(request=request) - - # Handle the response - print(response) - -# [END config_v1_generated_Config_ExportDeploymentStatefile_async] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_export_deployment_statefile_sync.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_export_deployment_statefile_sync.py deleted file mode 100644 index 6634416cb20a..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_export_deployment_statefile_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- 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 code. DO NOT EDIT! -# -# Snippet for ExportDeploymentStatefile -# 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-config - - -# [START config_v1_generated_Config_ExportDeploymentStatefile_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 config_v1 - - -def sample_export_deployment_statefile(): - # Create a client - client = config_v1.ConfigClient() - - # Initialize request argument(s) - request = config_v1.ExportDeploymentStatefileRequest( - parent="parent_value", - ) - - # Make the request - response = client.export_deployment_statefile(request=request) - - # Handle the response - print(response) - -# [END config_v1_generated_Config_ExportDeploymentStatefile_sync] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_export_lock_info_async.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_export_lock_info_async.py deleted file mode 100644 index 5cb010808733..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_export_lock_info_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- 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 code. DO NOT EDIT! -# -# Snippet for ExportLockInfo -# 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-config - - -# [START config_v1_generated_Config_ExportLockInfo_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 config_v1 - - -async def sample_export_lock_info(): - # Create a client - client = config_v1.ConfigAsyncClient() - - # Initialize request argument(s) - request = config_v1.ExportLockInfoRequest( - name="name_value", - ) - - # Make the request - response = await client.export_lock_info(request=request) - - # Handle the response - print(response) - -# [END config_v1_generated_Config_ExportLockInfo_async] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_export_lock_info_sync.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_export_lock_info_sync.py deleted file mode 100644 index cbe67eecd362..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_export_lock_info_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- 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 code. DO NOT EDIT! -# -# Snippet for ExportLockInfo -# 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-config - - -# [START config_v1_generated_Config_ExportLockInfo_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 config_v1 - - -def sample_export_lock_info(): - # Create a client - client = config_v1.ConfigClient() - - # Initialize request argument(s) - request = config_v1.ExportLockInfoRequest( - name="name_value", - ) - - # Make the request - response = client.export_lock_info(request=request) - - # Handle the response - print(response) - -# [END config_v1_generated_Config_ExportLockInfo_sync] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_export_preview_result_async.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_export_preview_result_async.py deleted file mode 100644 index 5343e17a6f7a..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_export_preview_result_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- 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 code. DO NOT EDIT! -# -# Snippet for ExportPreviewResult -# 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-config - - -# [START config_v1_generated_Config_ExportPreviewResult_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 config_v1 - - -async def sample_export_preview_result(): - # Create a client - client = config_v1.ConfigAsyncClient() - - # Initialize request argument(s) - request = config_v1.ExportPreviewResultRequest( - parent="parent_value", - ) - - # Make the request - response = await client.export_preview_result(request=request) - - # Handle the response - print(response) - -# [END config_v1_generated_Config_ExportPreviewResult_async] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_export_preview_result_sync.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_export_preview_result_sync.py deleted file mode 100644 index 3ef8a42c2272..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_export_preview_result_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- 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 code. DO NOT EDIT! -# -# Snippet for ExportPreviewResult -# 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-config - - -# [START config_v1_generated_Config_ExportPreviewResult_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 config_v1 - - -def sample_export_preview_result(): - # Create a client - client = config_v1.ConfigClient() - - # Initialize request argument(s) - request = config_v1.ExportPreviewResultRequest( - parent="parent_value", - ) - - # Make the request - response = client.export_preview_result(request=request) - - # Handle the response - print(response) - -# [END config_v1_generated_Config_ExportPreviewResult_sync] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_export_revision_statefile_async.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_export_revision_statefile_async.py deleted file mode 100644 index 6297828ad4fb..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_export_revision_statefile_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- 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 code. DO NOT EDIT! -# -# Snippet for ExportRevisionStatefile -# 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-config - - -# [START config_v1_generated_Config_ExportRevisionStatefile_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 config_v1 - - -async def sample_export_revision_statefile(): - # Create a client - client = config_v1.ConfigAsyncClient() - - # Initialize request argument(s) - request = config_v1.ExportRevisionStatefileRequest( - parent="parent_value", - ) - - # Make the request - response = await client.export_revision_statefile(request=request) - - # Handle the response - print(response) - -# [END config_v1_generated_Config_ExportRevisionStatefile_async] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_export_revision_statefile_sync.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_export_revision_statefile_sync.py deleted file mode 100644 index 2a3eda077104..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_export_revision_statefile_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- 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 code. DO NOT EDIT! -# -# Snippet for ExportRevisionStatefile -# 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-config - - -# [START config_v1_generated_Config_ExportRevisionStatefile_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 config_v1 - - -def sample_export_revision_statefile(): - # Create a client - client = config_v1.ConfigClient() - - # Initialize request argument(s) - request = config_v1.ExportRevisionStatefileRequest( - parent="parent_value", - ) - - # Make the request - response = client.export_revision_statefile(request=request) - - # Handle the response - print(response) - -# [END config_v1_generated_Config_ExportRevisionStatefile_sync] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_deployment_async.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_deployment_async.py deleted file mode 100644 index db2fdc05e334..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_deployment_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- 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 code. DO NOT EDIT! -# -# Snippet for GetDeployment -# 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-config - - -# [START config_v1_generated_Config_GetDeployment_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 config_v1 - - -async def sample_get_deployment(): - # Create a client - client = config_v1.ConfigAsyncClient() - - # Initialize request argument(s) - request = config_v1.GetDeploymentRequest( - name="name_value", - ) - - # Make the request - response = await client.get_deployment(request=request) - - # Handle the response - print(response) - -# [END config_v1_generated_Config_GetDeployment_async] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_deployment_sync.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_deployment_sync.py deleted file mode 100644 index f25109b58523..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_deployment_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- 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 code. DO NOT EDIT! -# -# Snippet for GetDeployment -# 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-config - - -# [START config_v1_generated_Config_GetDeployment_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 config_v1 - - -def sample_get_deployment(): - # Create a client - client = config_v1.ConfigClient() - - # Initialize request argument(s) - request = config_v1.GetDeploymentRequest( - name="name_value", - ) - - # Make the request - response = client.get_deployment(request=request) - - # Handle the response - print(response) - -# [END config_v1_generated_Config_GetDeployment_sync] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_preview_async.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_preview_async.py deleted file mode 100644 index fc9d5349b9bc..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_preview_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- 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 code. DO NOT EDIT! -# -# Snippet for GetPreview -# 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-config - - -# [START config_v1_generated_Config_GetPreview_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 config_v1 - - -async def sample_get_preview(): - # Create a client - client = config_v1.ConfigAsyncClient() - - # Initialize request argument(s) - request = config_v1.GetPreviewRequest( - name="name_value", - ) - - # Make the request - response = await client.get_preview(request=request) - - # Handle the response - print(response) - -# [END config_v1_generated_Config_GetPreview_async] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_preview_sync.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_preview_sync.py deleted file mode 100644 index cb569e2fee4a..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_preview_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- 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 code. DO NOT EDIT! -# -# Snippet for GetPreview -# 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-config - - -# [START config_v1_generated_Config_GetPreview_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 config_v1 - - -def sample_get_preview(): - # Create a client - client = config_v1.ConfigClient() - - # Initialize request argument(s) - request = config_v1.GetPreviewRequest( - name="name_value", - ) - - # Make the request - response = client.get_preview(request=request) - - # Handle the response - print(response) - -# [END config_v1_generated_Config_GetPreview_sync] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_resource_async.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_resource_async.py deleted file mode 100644 index 0da5b8a568bf..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_resource_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- 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 code. DO NOT EDIT! -# -# Snippet for GetResource -# 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-config - - -# [START config_v1_generated_Config_GetResource_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 config_v1 - - -async def sample_get_resource(): - # Create a client - client = config_v1.ConfigAsyncClient() - - # Initialize request argument(s) - request = config_v1.GetResourceRequest( - name="name_value", - ) - - # Make the request - response = await client.get_resource(request=request) - - # Handle the response - print(response) - -# [END config_v1_generated_Config_GetResource_async] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_resource_change_async.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_resource_change_async.py deleted file mode 100644 index e5ae15f06e73..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_resource_change_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- 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 code. DO NOT EDIT! -# -# Snippet for GetResourceChange -# 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-config - - -# [START config_v1_generated_Config_GetResourceChange_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 config_v1 - - -async def sample_get_resource_change(): - # Create a client - client = config_v1.ConfigAsyncClient() - - # Initialize request argument(s) - request = config_v1.GetResourceChangeRequest( - name="name_value", - ) - - # Make the request - response = await client.get_resource_change(request=request) - - # Handle the response - print(response) - -# [END config_v1_generated_Config_GetResourceChange_async] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_resource_change_sync.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_resource_change_sync.py deleted file mode 100644 index 9d9f76af84ab..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_resource_change_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- 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 code. DO NOT EDIT! -# -# Snippet for GetResourceChange -# 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-config - - -# [START config_v1_generated_Config_GetResourceChange_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 config_v1 - - -def sample_get_resource_change(): - # Create a client - client = config_v1.ConfigClient() - - # Initialize request argument(s) - request = config_v1.GetResourceChangeRequest( - name="name_value", - ) - - # Make the request - response = client.get_resource_change(request=request) - - # Handle the response - print(response) - -# [END config_v1_generated_Config_GetResourceChange_sync] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_resource_drift_async.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_resource_drift_async.py deleted file mode 100644 index 3383906e899f..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_resource_drift_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- 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 code. DO NOT EDIT! -# -# Snippet for GetResourceDrift -# 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-config - - -# [START config_v1_generated_Config_GetResourceDrift_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 config_v1 - - -async def sample_get_resource_drift(): - # Create a client - client = config_v1.ConfigAsyncClient() - - # Initialize request argument(s) - request = config_v1.GetResourceDriftRequest( - name="name_value", - ) - - # Make the request - response = await client.get_resource_drift(request=request) - - # Handle the response - print(response) - -# [END config_v1_generated_Config_GetResourceDrift_async] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_resource_drift_sync.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_resource_drift_sync.py deleted file mode 100644 index 0747cff56542..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_resource_drift_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- 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 code. DO NOT EDIT! -# -# Snippet for GetResourceDrift -# 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-config - - -# [START config_v1_generated_Config_GetResourceDrift_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 config_v1 - - -def sample_get_resource_drift(): - # Create a client - client = config_v1.ConfigClient() - - # Initialize request argument(s) - request = config_v1.GetResourceDriftRequest( - name="name_value", - ) - - # Make the request - response = client.get_resource_drift(request=request) - - # Handle the response - print(response) - -# [END config_v1_generated_Config_GetResourceDrift_sync] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_resource_sync.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_resource_sync.py deleted file mode 100644 index daa073ed2aca..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_resource_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- 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 code. DO NOT EDIT! -# -# Snippet for GetResource -# 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-config - - -# [START config_v1_generated_Config_GetResource_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 config_v1 - - -def sample_get_resource(): - # Create a client - client = config_v1.ConfigClient() - - # Initialize request argument(s) - request = config_v1.GetResourceRequest( - name="name_value", - ) - - # Make the request - response = client.get_resource(request=request) - - # Handle the response - print(response) - -# [END config_v1_generated_Config_GetResource_sync] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_revision_async.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_revision_async.py deleted file mode 100644 index 57d693b81926..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_revision_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- 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 code. DO NOT EDIT! -# -# Snippet for GetRevision -# 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-config - - -# [START config_v1_generated_Config_GetRevision_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 config_v1 - - -async def sample_get_revision(): - # Create a client - client = config_v1.ConfigAsyncClient() - - # Initialize request argument(s) - request = config_v1.GetRevisionRequest( - name="name_value", - ) - - # Make the request - response = await client.get_revision(request=request) - - # Handle the response - print(response) - -# [END config_v1_generated_Config_GetRevision_async] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_revision_sync.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_revision_sync.py deleted file mode 100644 index 98996604e6ac..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_revision_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- 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 code. DO NOT EDIT! -# -# Snippet for GetRevision -# 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-config - - -# [START config_v1_generated_Config_GetRevision_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 config_v1 - - -def sample_get_revision(): - # Create a client - client = config_v1.ConfigClient() - - # Initialize request argument(s) - request = config_v1.GetRevisionRequest( - name="name_value", - ) - - # Make the request - response = client.get_revision(request=request) - - # Handle the response - print(response) - -# [END config_v1_generated_Config_GetRevision_sync] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_terraform_version_async.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_terraform_version_async.py deleted file mode 100644 index b7529c444505..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_terraform_version_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- 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 code. DO NOT EDIT! -# -# Snippet for GetTerraformVersion -# 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-config - - -# [START config_v1_generated_Config_GetTerraformVersion_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 config_v1 - - -async def sample_get_terraform_version(): - # Create a client - client = config_v1.ConfigAsyncClient() - - # Initialize request argument(s) - request = config_v1.GetTerraformVersionRequest( - name="name_value", - ) - - # Make the request - response = await client.get_terraform_version(request=request) - - # Handle the response - print(response) - -# [END config_v1_generated_Config_GetTerraformVersion_async] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_terraform_version_sync.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_terraform_version_sync.py deleted file mode 100644 index 83ed8de8a446..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_terraform_version_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- 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 code. DO NOT EDIT! -# -# Snippet for GetTerraformVersion -# 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-config - - -# [START config_v1_generated_Config_GetTerraformVersion_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 config_v1 - - -def sample_get_terraform_version(): - # Create a client - client = config_v1.ConfigClient() - - # Initialize request argument(s) - request = config_v1.GetTerraformVersionRequest( - name="name_value", - ) - - # Make the request - response = client.get_terraform_version(request=request) - - # Handle the response - print(response) - -# [END config_v1_generated_Config_GetTerraformVersion_sync] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_import_statefile_async.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_import_statefile_async.py deleted file mode 100644 index f12777fe9b39..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_import_statefile_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- 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 code. DO NOT EDIT! -# -# Snippet for ImportStatefile -# 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-config - - -# [START config_v1_generated_Config_ImportStatefile_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 config_v1 - - -async def sample_import_statefile(): - # Create a client - client = config_v1.ConfigAsyncClient() - - # Initialize request argument(s) - request = config_v1.ImportStatefileRequest( - parent="parent_value", - lock_id=725, - ) - - # Make the request - response = await client.import_statefile(request=request) - - # Handle the response - print(response) - -# [END config_v1_generated_Config_ImportStatefile_async] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_import_statefile_sync.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_import_statefile_sync.py deleted file mode 100644 index 13b7deffff7a..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_import_statefile_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- 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 code. DO NOT EDIT! -# -# Snippet for ImportStatefile -# 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-config - - -# [START config_v1_generated_Config_ImportStatefile_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 config_v1 - - -def sample_import_statefile(): - # Create a client - client = config_v1.ConfigClient() - - # Initialize request argument(s) - request = config_v1.ImportStatefileRequest( - parent="parent_value", - lock_id=725, - ) - - # Make the request - response = client.import_statefile(request=request) - - # Handle the response - print(response) - -# [END config_v1_generated_Config_ImportStatefile_sync] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_deployments_async.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_deployments_async.py deleted file mode 100644 index e854d0b85cb8..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_deployments_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- 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 code. DO NOT EDIT! -# -# Snippet for ListDeployments -# 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-config - - -# [START config_v1_generated_Config_ListDeployments_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 config_v1 - - -async def sample_list_deployments(): - # Create a client - client = config_v1.ConfigAsyncClient() - - # Initialize request argument(s) - request = config_v1.ListDeploymentsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_deployments(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END config_v1_generated_Config_ListDeployments_async] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_deployments_sync.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_deployments_sync.py deleted file mode 100644 index 963621cb81f2..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_deployments_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- 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 code. DO NOT EDIT! -# -# Snippet for ListDeployments -# 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-config - - -# [START config_v1_generated_Config_ListDeployments_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 config_v1 - - -def sample_list_deployments(): - # Create a client - client = config_v1.ConfigClient() - - # Initialize request argument(s) - request = config_v1.ListDeploymentsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_deployments(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END config_v1_generated_Config_ListDeployments_sync] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_previews_async.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_previews_async.py deleted file mode 100644 index 42602ac89455..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_previews_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- 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 code. DO NOT EDIT! -# -# Snippet for ListPreviews -# 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-config - - -# [START config_v1_generated_Config_ListPreviews_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 config_v1 - - -async def sample_list_previews(): - # Create a client - client = config_v1.ConfigAsyncClient() - - # Initialize request argument(s) - request = config_v1.ListPreviewsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_previews(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END config_v1_generated_Config_ListPreviews_async] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_previews_sync.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_previews_sync.py deleted file mode 100644 index a600f538aaa8..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_previews_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- 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 code. DO NOT EDIT! -# -# Snippet for ListPreviews -# 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-config - - -# [START config_v1_generated_Config_ListPreviews_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 config_v1 - - -def sample_list_previews(): - # Create a client - client = config_v1.ConfigClient() - - # Initialize request argument(s) - request = config_v1.ListPreviewsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_previews(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END config_v1_generated_Config_ListPreviews_sync] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_resource_changes_async.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_resource_changes_async.py deleted file mode 100644 index 9d6aa11137f8..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_resource_changes_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- 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 code. DO NOT EDIT! -# -# Snippet for ListResourceChanges -# 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-config - - -# [START config_v1_generated_Config_ListResourceChanges_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 config_v1 - - -async def sample_list_resource_changes(): - # Create a client - client = config_v1.ConfigAsyncClient() - - # Initialize request argument(s) - request = config_v1.ListResourceChangesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_resource_changes(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END config_v1_generated_Config_ListResourceChanges_async] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_resource_changes_sync.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_resource_changes_sync.py deleted file mode 100644 index 28df72a2c143..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_resource_changes_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- 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 code. DO NOT EDIT! -# -# Snippet for ListResourceChanges -# 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-config - - -# [START config_v1_generated_Config_ListResourceChanges_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 config_v1 - - -def sample_list_resource_changes(): - # Create a client - client = config_v1.ConfigClient() - - # Initialize request argument(s) - request = config_v1.ListResourceChangesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_resource_changes(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END config_v1_generated_Config_ListResourceChanges_sync] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_resource_drifts_async.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_resource_drifts_async.py deleted file mode 100644 index 3ae0be582ae2..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_resource_drifts_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- 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 code. DO NOT EDIT! -# -# Snippet for ListResourceDrifts -# 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-config - - -# [START config_v1_generated_Config_ListResourceDrifts_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 config_v1 - - -async def sample_list_resource_drifts(): - # Create a client - client = config_v1.ConfigAsyncClient() - - # Initialize request argument(s) - request = config_v1.ListResourceDriftsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_resource_drifts(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END config_v1_generated_Config_ListResourceDrifts_async] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_resource_drifts_sync.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_resource_drifts_sync.py deleted file mode 100644 index 46370dc55987..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_resource_drifts_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- 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 code. DO NOT EDIT! -# -# Snippet for ListResourceDrifts -# 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-config - - -# [START config_v1_generated_Config_ListResourceDrifts_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 config_v1 - - -def sample_list_resource_drifts(): - # Create a client - client = config_v1.ConfigClient() - - # Initialize request argument(s) - request = config_v1.ListResourceDriftsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_resource_drifts(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END config_v1_generated_Config_ListResourceDrifts_sync] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_resources_async.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_resources_async.py deleted file mode 100644 index 3dcf01ff5411..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_resources_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- 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 code. DO NOT EDIT! -# -# Snippet for ListResources -# 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-config - - -# [START config_v1_generated_Config_ListResources_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 config_v1 - - -async def sample_list_resources(): - # Create a client - client = config_v1.ConfigAsyncClient() - - # Initialize request argument(s) - request = config_v1.ListResourcesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_resources(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END config_v1_generated_Config_ListResources_async] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_resources_sync.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_resources_sync.py deleted file mode 100644 index 1846ee47b345..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_resources_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- 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 code. DO NOT EDIT! -# -# Snippet for ListResources -# 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-config - - -# [START config_v1_generated_Config_ListResources_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 config_v1 - - -def sample_list_resources(): - # Create a client - client = config_v1.ConfigClient() - - # Initialize request argument(s) - request = config_v1.ListResourcesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_resources(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END config_v1_generated_Config_ListResources_sync] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_revisions_async.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_revisions_async.py deleted file mode 100644 index 3ae25389e89d..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_revisions_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- 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 code. DO NOT EDIT! -# -# Snippet for ListRevisions -# 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-config - - -# [START config_v1_generated_Config_ListRevisions_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 config_v1 - - -async def sample_list_revisions(): - # Create a client - client = config_v1.ConfigAsyncClient() - - # Initialize request argument(s) - request = config_v1.ListRevisionsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_revisions(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END config_v1_generated_Config_ListRevisions_async] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_revisions_sync.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_revisions_sync.py deleted file mode 100644 index 8ac8caa1aa6b..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_revisions_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- 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 code. DO NOT EDIT! -# -# Snippet for ListRevisions -# 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-config - - -# [START config_v1_generated_Config_ListRevisions_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 config_v1 - - -def sample_list_revisions(): - # Create a client - client = config_v1.ConfigClient() - - # Initialize request argument(s) - request = config_v1.ListRevisionsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_revisions(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END config_v1_generated_Config_ListRevisions_sync] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_terraform_versions_async.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_terraform_versions_async.py deleted file mode 100644 index eacac7c01eec..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_terraform_versions_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- 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 code. DO NOT EDIT! -# -# Snippet for ListTerraformVersions -# 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-config - - -# [START config_v1_generated_Config_ListTerraformVersions_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 config_v1 - - -async def sample_list_terraform_versions(): - # Create a client - client = config_v1.ConfigAsyncClient() - - # Initialize request argument(s) - request = config_v1.ListTerraformVersionsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_terraform_versions(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END config_v1_generated_Config_ListTerraformVersions_async] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_terraform_versions_sync.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_terraform_versions_sync.py deleted file mode 100644 index 127610432e1d..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_terraform_versions_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- 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 code. DO NOT EDIT! -# -# Snippet for ListTerraformVersions -# 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-config - - -# [START config_v1_generated_Config_ListTerraformVersions_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 config_v1 - - -def sample_list_terraform_versions(): - # Create a client - client = config_v1.ConfigClient() - - # Initialize request argument(s) - request = config_v1.ListTerraformVersionsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_terraform_versions(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END config_v1_generated_Config_ListTerraformVersions_sync] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_lock_deployment_async.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_lock_deployment_async.py deleted file mode 100644 index 53b5509a1ce3..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_lock_deployment_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- 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 code. DO NOT EDIT! -# -# Snippet for LockDeployment -# 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-config - - -# [START config_v1_generated_Config_LockDeployment_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 config_v1 - - -async def sample_lock_deployment(): - # Create a client - client = config_v1.ConfigAsyncClient() - - # Initialize request argument(s) - request = config_v1.LockDeploymentRequest( - name="name_value", - ) - - # Make the request - operation = client.lock_deployment(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END config_v1_generated_Config_LockDeployment_async] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_lock_deployment_sync.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_lock_deployment_sync.py deleted file mode 100644 index 1fbf51737107..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_lock_deployment_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- 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 code. DO NOT EDIT! -# -# Snippet for LockDeployment -# 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-config - - -# [START config_v1_generated_Config_LockDeployment_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 config_v1 - - -def sample_lock_deployment(): - # Create a client - client = config_v1.ConfigClient() - - # Initialize request argument(s) - request = config_v1.LockDeploymentRequest( - name="name_value", - ) - - # Make the request - operation = client.lock_deployment(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END config_v1_generated_Config_LockDeployment_sync] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_unlock_deployment_async.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_unlock_deployment_async.py deleted file mode 100644 index c332f1cfb950..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_unlock_deployment_async.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- 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 code. DO NOT EDIT! -# -# Snippet for UnlockDeployment -# 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-config - - -# [START config_v1_generated_Config_UnlockDeployment_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 config_v1 - - -async def sample_unlock_deployment(): - # Create a client - client = config_v1.ConfigAsyncClient() - - # Initialize request argument(s) - request = config_v1.UnlockDeploymentRequest( - name="name_value", - lock_id=725, - ) - - # Make the request - operation = client.unlock_deployment(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END config_v1_generated_Config_UnlockDeployment_async] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_unlock_deployment_sync.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_unlock_deployment_sync.py deleted file mode 100644 index 2ce243fe0ef2..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_unlock_deployment_sync.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- 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 code. DO NOT EDIT! -# -# Snippet for UnlockDeployment -# 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-config - - -# [START config_v1_generated_Config_UnlockDeployment_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 config_v1 - - -def sample_unlock_deployment(): - # Create a client - client = config_v1.ConfigClient() - - # Initialize request argument(s) - request = config_v1.UnlockDeploymentRequest( - name="name_value", - lock_id=725, - ) - - # Make the request - operation = client.unlock_deployment(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END config_v1_generated_Config_UnlockDeployment_sync] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_update_deployment_async.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_update_deployment_async.py deleted file mode 100644 index 8961f5f2d773..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_update_deployment_async.py +++ /dev/null @@ -1,59 +0,0 @@ -# -*- 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 code. DO NOT EDIT! -# -# Snippet for UpdateDeployment -# 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-config - - -# [START config_v1_generated_Config_UpdateDeployment_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 config_v1 - - -async def sample_update_deployment(): - # Create a client - client = config_v1.ConfigAsyncClient() - - # Initialize request argument(s) - deployment = config_v1.Deployment() - deployment.terraform_blueprint.gcs_source = "gcs_source_value" - - request = config_v1.UpdateDeploymentRequest( - deployment=deployment, - ) - - # Make the request - operation = client.update_deployment(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END config_v1_generated_Config_UpdateDeployment_async] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_update_deployment_sync.py b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_update_deployment_sync.py deleted file mode 100644 index 72639735ea78..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_update_deployment_sync.py +++ /dev/null @@ -1,59 +0,0 @@ -# -*- 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 code. DO NOT EDIT! -# -# Snippet for UpdateDeployment -# 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-config - - -# [START config_v1_generated_Config_UpdateDeployment_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 config_v1 - - -def sample_update_deployment(): - # Create a client - client = config_v1.ConfigClient() - - # Initialize request argument(s) - deployment = config_v1.Deployment() - deployment.terraform_blueprint.gcs_source = "gcs_source_value" - - request = config_v1.UpdateDeploymentRequest( - deployment=deployment, - ) - - # Make the request - operation = client.update_deployment(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END config_v1_generated_Config_UpdateDeployment_sync] diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/snippet_metadata_google.cloud.config.v1.json b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/snippet_metadata_google.cloud.config.v1.json deleted file mode 100644 index 8a55b66d4f2f..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/snippet_metadata_google.cloud.config.v1.json +++ /dev/null @@ -1,4380 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.cloud.config.v1", - "version": "v1" - } - ], - "language": "PYTHON", - "name": "google-cloud-config", - "version": "0.1.0" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.config_v1.ConfigAsyncClient", - "shortName": "ConfigAsyncClient" - }, - "fullName": "google.cloud.config_v1.ConfigAsyncClient.create_deployment", - "method": { - "fullName": "google.cloud.config.v1.Config.CreateDeployment", - "service": { - "fullName": "google.cloud.config.v1.Config", - "shortName": "Config" - }, - "shortName": "CreateDeployment" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.config_v1.types.CreateDeploymentRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "deployment", - "type": "google.cloud.config_v1.types.Deployment" - }, - { - "name": "deployment_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_deployment" - }, - "description": "Sample for CreateDeployment", - "file": "config_v1_generated_config_create_deployment_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "config_v1_generated_Config_CreateDeployment_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": "config_v1_generated_config_create_deployment_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.config_v1.ConfigClient", - "shortName": "ConfigClient" - }, - "fullName": "google.cloud.config_v1.ConfigClient.create_deployment", - "method": { - "fullName": "google.cloud.config.v1.Config.CreateDeployment", - "service": { - "fullName": "google.cloud.config.v1.Config", - "shortName": "Config" - }, - "shortName": "CreateDeployment" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.config_v1.types.CreateDeploymentRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "deployment", - "type": "google.cloud.config_v1.types.Deployment" - }, - { - "name": "deployment_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_deployment" - }, - "description": "Sample for CreateDeployment", - "file": "config_v1_generated_config_create_deployment_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "config_v1_generated_Config_CreateDeployment_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": "config_v1_generated_config_create_deployment_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.config_v1.ConfigAsyncClient", - "shortName": "ConfigAsyncClient" - }, - "fullName": "google.cloud.config_v1.ConfigAsyncClient.create_preview", - "method": { - "fullName": "google.cloud.config.v1.Config.CreatePreview", - "service": { - "fullName": "google.cloud.config.v1.Config", - "shortName": "Config" - }, - "shortName": "CreatePreview" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.config_v1.types.CreatePreviewRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "preview", - "type": "google.cloud.config_v1.types.Preview" - }, - { - "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_preview" - }, - "description": "Sample for CreatePreview", - "file": "config_v1_generated_config_create_preview_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "config_v1_generated_Config_CreatePreview_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": "config_v1_generated_config_create_preview_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.config_v1.ConfigClient", - "shortName": "ConfigClient" - }, - "fullName": "google.cloud.config_v1.ConfigClient.create_preview", - "method": { - "fullName": "google.cloud.config.v1.Config.CreatePreview", - "service": { - "fullName": "google.cloud.config.v1.Config", - "shortName": "Config" - }, - "shortName": "CreatePreview" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.config_v1.types.CreatePreviewRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "preview", - "type": "google.cloud.config_v1.types.Preview" - }, - { - "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_preview" - }, - "description": "Sample for CreatePreview", - "file": "config_v1_generated_config_create_preview_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "config_v1_generated_Config_CreatePreview_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": "config_v1_generated_config_create_preview_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.config_v1.ConfigAsyncClient", - "shortName": "ConfigAsyncClient" - }, - "fullName": "google.cloud.config_v1.ConfigAsyncClient.delete_deployment", - "method": { - "fullName": "google.cloud.config.v1.Config.DeleteDeployment", - "service": { - "fullName": "google.cloud.config.v1.Config", - "shortName": "Config" - }, - "shortName": "DeleteDeployment" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.config_v1.types.DeleteDeploymentRequest" - }, - { - "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_deployment" - }, - "description": "Sample for DeleteDeployment", - "file": "config_v1_generated_config_delete_deployment_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "config_v1_generated_Config_DeleteDeployment_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": "config_v1_generated_config_delete_deployment_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.config_v1.ConfigClient", - "shortName": "ConfigClient" - }, - "fullName": "google.cloud.config_v1.ConfigClient.delete_deployment", - "method": { - "fullName": "google.cloud.config.v1.Config.DeleteDeployment", - "service": { - "fullName": "google.cloud.config.v1.Config", - "shortName": "Config" - }, - "shortName": "DeleteDeployment" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.config_v1.types.DeleteDeploymentRequest" - }, - { - "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_deployment" - }, - "description": "Sample for DeleteDeployment", - "file": "config_v1_generated_config_delete_deployment_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "config_v1_generated_Config_DeleteDeployment_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": "config_v1_generated_config_delete_deployment_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.config_v1.ConfigAsyncClient", - "shortName": "ConfigAsyncClient" - }, - "fullName": "google.cloud.config_v1.ConfigAsyncClient.delete_preview", - "method": { - "fullName": "google.cloud.config.v1.Config.DeletePreview", - "service": { - "fullName": "google.cloud.config.v1.Config", - "shortName": "Config" - }, - "shortName": "DeletePreview" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.config_v1.types.DeletePreviewRequest" - }, - { - "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_preview" - }, - "description": "Sample for DeletePreview", - "file": "config_v1_generated_config_delete_preview_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "config_v1_generated_Config_DeletePreview_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": "config_v1_generated_config_delete_preview_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.config_v1.ConfigClient", - "shortName": "ConfigClient" - }, - "fullName": "google.cloud.config_v1.ConfigClient.delete_preview", - "method": { - "fullName": "google.cloud.config.v1.Config.DeletePreview", - "service": { - "fullName": "google.cloud.config.v1.Config", - "shortName": "Config" - }, - "shortName": "DeletePreview" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.config_v1.types.DeletePreviewRequest" - }, - { - "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_preview" - }, - "description": "Sample for DeletePreview", - "file": "config_v1_generated_config_delete_preview_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "config_v1_generated_Config_DeletePreview_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": "config_v1_generated_config_delete_preview_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.config_v1.ConfigAsyncClient", - "shortName": "ConfigAsyncClient" - }, - "fullName": "google.cloud.config_v1.ConfigAsyncClient.delete_statefile", - "method": { - "fullName": "google.cloud.config.v1.Config.DeleteStatefile", - "service": { - "fullName": "google.cloud.config.v1.Config", - "shortName": "Config" - }, - "shortName": "DeleteStatefile" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.config_v1.types.DeleteStatefileRequest" - }, - { - "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_statefile" - }, - "description": "Sample for DeleteStatefile", - "file": "config_v1_generated_config_delete_statefile_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "config_v1_generated_Config_DeleteStatefile_async", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "type": "RESPONSE_HANDLING" - } - ], - "title": "config_v1_generated_config_delete_statefile_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.config_v1.ConfigClient", - "shortName": "ConfigClient" - }, - "fullName": "google.cloud.config_v1.ConfigClient.delete_statefile", - "method": { - "fullName": "google.cloud.config.v1.Config.DeleteStatefile", - "service": { - "fullName": "google.cloud.config.v1.Config", - "shortName": "Config" - }, - "shortName": "DeleteStatefile" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.config_v1.types.DeleteStatefileRequest" - }, - { - "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_statefile" - }, - "description": "Sample for DeleteStatefile", - "file": "config_v1_generated_config_delete_statefile_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "config_v1_generated_Config_DeleteStatefile_sync", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "type": "RESPONSE_HANDLING" - } - ], - "title": "config_v1_generated_config_delete_statefile_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.config_v1.ConfigAsyncClient", - "shortName": "ConfigAsyncClient" - }, - "fullName": "google.cloud.config_v1.ConfigAsyncClient.export_deployment_statefile", - "method": { - "fullName": "google.cloud.config.v1.Config.ExportDeploymentStatefile", - "service": { - "fullName": "google.cloud.config.v1.Config", - "shortName": "Config" - }, - "shortName": "ExportDeploymentStatefile" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.config_v1.types.ExportDeploymentStatefileRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.config_v1.types.Statefile", - "shortName": "export_deployment_statefile" - }, - "description": "Sample for ExportDeploymentStatefile", - "file": "config_v1_generated_config_export_deployment_statefile_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "config_v1_generated_Config_ExportDeploymentStatefile_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": "config_v1_generated_config_export_deployment_statefile_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.config_v1.ConfigClient", - "shortName": "ConfigClient" - }, - "fullName": "google.cloud.config_v1.ConfigClient.export_deployment_statefile", - "method": { - "fullName": "google.cloud.config.v1.Config.ExportDeploymentStatefile", - "service": { - "fullName": "google.cloud.config.v1.Config", - "shortName": "Config" - }, - "shortName": "ExportDeploymentStatefile" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.config_v1.types.ExportDeploymentStatefileRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.config_v1.types.Statefile", - "shortName": "export_deployment_statefile" - }, - "description": "Sample for ExportDeploymentStatefile", - "file": "config_v1_generated_config_export_deployment_statefile_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "config_v1_generated_Config_ExportDeploymentStatefile_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": "config_v1_generated_config_export_deployment_statefile_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.config_v1.ConfigAsyncClient", - "shortName": "ConfigAsyncClient" - }, - "fullName": "google.cloud.config_v1.ConfigAsyncClient.export_lock_info", - "method": { - "fullName": "google.cloud.config.v1.Config.ExportLockInfo", - "service": { - "fullName": "google.cloud.config.v1.Config", - "shortName": "Config" - }, - "shortName": "ExportLockInfo" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.config_v1.types.ExportLockInfoRequest" - }, - { - "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.config_v1.types.LockInfo", - "shortName": "export_lock_info" - }, - "description": "Sample for ExportLockInfo", - "file": "config_v1_generated_config_export_lock_info_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "config_v1_generated_Config_ExportLockInfo_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": "config_v1_generated_config_export_lock_info_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.config_v1.ConfigClient", - "shortName": "ConfigClient" - }, - "fullName": "google.cloud.config_v1.ConfigClient.export_lock_info", - "method": { - "fullName": "google.cloud.config.v1.Config.ExportLockInfo", - "service": { - "fullName": "google.cloud.config.v1.Config", - "shortName": "Config" - }, - "shortName": "ExportLockInfo" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.config_v1.types.ExportLockInfoRequest" - }, - { - "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.config_v1.types.LockInfo", - "shortName": "export_lock_info" - }, - "description": "Sample for ExportLockInfo", - "file": "config_v1_generated_config_export_lock_info_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "config_v1_generated_Config_ExportLockInfo_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": "config_v1_generated_config_export_lock_info_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.config_v1.ConfigAsyncClient", - "shortName": "ConfigAsyncClient" - }, - "fullName": "google.cloud.config_v1.ConfigAsyncClient.export_preview_result", - "method": { - "fullName": "google.cloud.config.v1.Config.ExportPreviewResult", - "service": { - "fullName": "google.cloud.config.v1.Config", - "shortName": "Config" - }, - "shortName": "ExportPreviewResult" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.config_v1.types.ExportPreviewResultRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.config_v1.types.ExportPreviewResultResponse", - "shortName": "export_preview_result" - }, - "description": "Sample for ExportPreviewResult", - "file": "config_v1_generated_config_export_preview_result_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "config_v1_generated_Config_ExportPreviewResult_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": "config_v1_generated_config_export_preview_result_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.config_v1.ConfigClient", - "shortName": "ConfigClient" - }, - "fullName": "google.cloud.config_v1.ConfigClient.export_preview_result", - "method": { - "fullName": "google.cloud.config.v1.Config.ExportPreviewResult", - "service": { - "fullName": "google.cloud.config.v1.Config", - "shortName": "Config" - }, - "shortName": "ExportPreviewResult" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.config_v1.types.ExportPreviewResultRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.config_v1.types.ExportPreviewResultResponse", - "shortName": "export_preview_result" - }, - "description": "Sample for ExportPreviewResult", - "file": "config_v1_generated_config_export_preview_result_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "config_v1_generated_Config_ExportPreviewResult_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": "config_v1_generated_config_export_preview_result_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.config_v1.ConfigAsyncClient", - "shortName": "ConfigAsyncClient" - }, - "fullName": "google.cloud.config_v1.ConfigAsyncClient.export_revision_statefile", - "method": { - "fullName": "google.cloud.config.v1.Config.ExportRevisionStatefile", - "service": { - "fullName": "google.cloud.config.v1.Config", - "shortName": "Config" - }, - "shortName": "ExportRevisionStatefile" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.config_v1.types.ExportRevisionStatefileRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.config_v1.types.Statefile", - "shortName": "export_revision_statefile" - }, - "description": "Sample for ExportRevisionStatefile", - "file": "config_v1_generated_config_export_revision_statefile_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "config_v1_generated_Config_ExportRevisionStatefile_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": "config_v1_generated_config_export_revision_statefile_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.config_v1.ConfigClient", - "shortName": "ConfigClient" - }, - "fullName": "google.cloud.config_v1.ConfigClient.export_revision_statefile", - "method": { - "fullName": "google.cloud.config.v1.Config.ExportRevisionStatefile", - "service": { - "fullName": "google.cloud.config.v1.Config", - "shortName": "Config" - }, - "shortName": "ExportRevisionStatefile" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.config_v1.types.ExportRevisionStatefileRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.config_v1.types.Statefile", - "shortName": "export_revision_statefile" - }, - "description": "Sample for ExportRevisionStatefile", - "file": "config_v1_generated_config_export_revision_statefile_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "config_v1_generated_Config_ExportRevisionStatefile_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": "config_v1_generated_config_export_revision_statefile_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.config_v1.ConfigAsyncClient", - "shortName": "ConfigAsyncClient" - }, - "fullName": "google.cloud.config_v1.ConfigAsyncClient.get_deployment", - "method": { - "fullName": "google.cloud.config.v1.Config.GetDeployment", - "service": { - "fullName": "google.cloud.config.v1.Config", - "shortName": "Config" - }, - "shortName": "GetDeployment" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.config_v1.types.GetDeploymentRequest" - }, - { - "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.config_v1.types.Deployment", - "shortName": "get_deployment" - }, - "description": "Sample for GetDeployment", - "file": "config_v1_generated_config_get_deployment_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "config_v1_generated_Config_GetDeployment_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": "config_v1_generated_config_get_deployment_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.config_v1.ConfigClient", - "shortName": "ConfigClient" - }, - "fullName": "google.cloud.config_v1.ConfigClient.get_deployment", - "method": { - "fullName": "google.cloud.config.v1.Config.GetDeployment", - "service": { - "fullName": "google.cloud.config.v1.Config", - "shortName": "Config" - }, - "shortName": "GetDeployment" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.config_v1.types.GetDeploymentRequest" - }, - { - "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.config_v1.types.Deployment", - "shortName": "get_deployment" - }, - "description": "Sample for GetDeployment", - "file": "config_v1_generated_config_get_deployment_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "config_v1_generated_Config_GetDeployment_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": "config_v1_generated_config_get_deployment_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.config_v1.ConfigAsyncClient", - "shortName": "ConfigAsyncClient" - }, - "fullName": "google.cloud.config_v1.ConfigAsyncClient.get_preview", - "method": { - "fullName": "google.cloud.config.v1.Config.GetPreview", - "service": { - "fullName": "google.cloud.config.v1.Config", - "shortName": "Config" - }, - "shortName": "GetPreview" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.config_v1.types.GetPreviewRequest" - }, - { - "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.config_v1.types.Preview", - "shortName": "get_preview" - }, - "description": "Sample for GetPreview", - "file": "config_v1_generated_config_get_preview_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "config_v1_generated_Config_GetPreview_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": "config_v1_generated_config_get_preview_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.config_v1.ConfigClient", - "shortName": "ConfigClient" - }, - "fullName": "google.cloud.config_v1.ConfigClient.get_preview", - "method": { - "fullName": "google.cloud.config.v1.Config.GetPreview", - "service": { - "fullName": "google.cloud.config.v1.Config", - "shortName": "Config" - }, - "shortName": "GetPreview" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.config_v1.types.GetPreviewRequest" - }, - { - "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.config_v1.types.Preview", - "shortName": "get_preview" - }, - "description": "Sample for GetPreview", - "file": "config_v1_generated_config_get_preview_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "config_v1_generated_Config_GetPreview_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": "config_v1_generated_config_get_preview_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.config_v1.ConfigAsyncClient", - "shortName": "ConfigAsyncClient" - }, - "fullName": "google.cloud.config_v1.ConfigAsyncClient.get_resource_change", - "method": { - "fullName": "google.cloud.config.v1.Config.GetResourceChange", - "service": { - "fullName": "google.cloud.config.v1.Config", - "shortName": "Config" - }, - "shortName": "GetResourceChange" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.config_v1.types.GetResourceChangeRequest" - }, - { - "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.config_v1.types.ResourceChange", - "shortName": "get_resource_change" - }, - "description": "Sample for GetResourceChange", - "file": "config_v1_generated_config_get_resource_change_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "config_v1_generated_Config_GetResourceChange_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": "config_v1_generated_config_get_resource_change_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.config_v1.ConfigClient", - "shortName": "ConfigClient" - }, - "fullName": "google.cloud.config_v1.ConfigClient.get_resource_change", - "method": { - "fullName": "google.cloud.config.v1.Config.GetResourceChange", - "service": { - "fullName": "google.cloud.config.v1.Config", - "shortName": "Config" - }, - "shortName": "GetResourceChange" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.config_v1.types.GetResourceChangeRequest" - }, - { - "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.config_v1.types.ResourceChange", - "shortName": "get_resource_change" - }, - "description": "Sample for GetResourceChange", - "file": "config_v1_generated_config_get_resource_change_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "config_v1_generated_Config_GetResourceChange_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": "config_v1_generated_config_get_resource_change_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.config_v1.ConfigAsyncClient", - "shortName": "ConfigAsyncClient" - }, - "fullName": "google.cloud.config_v1.ConfigAsyncClient.get_resource_drift", - "method": { - "fullName": "google.cloud.config.v1.Config.GetResourceDrift", - "service": { - "fullName": "google.cloud.config.v1.Config", - "shortName": "Config" - }, - "shortName": "GetResourceDrift" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.config_v1.types.GetResourceDriftRequest" - }, - { - "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.config_v1.types.ResourceDrift", - "shortName": "get_resource_drift" - }, - "description": "Sample for GetResourceDrift", - "file": "config_v1_generated_config_get_resource_drift_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "config_v1_generated_Config_GetResourceDrift_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": "config_v1_generated_config_get_resource_drift_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.config_v1.ConfigClient", - "shortName": "ConfigClient" - }, - "fullName": "google.cloud.config_v1.ConfigClient.get_resource_drift", - "method": { - "fullName": "google.cloud.config.v1.Config.GetResourceDrift", - "service": { - "fullName": "google.cloud.config.v1.Config", - "shortName": "Config" - }, - "shortName": "GetResourceDrift" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.config_v1.types.GetResourceDriftRequest" - }, - { - "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.config_v1.types.ResourceDrift", - "shortName": "get_resource_drift" - }, - "description": "Sample for GetResourceDrift", - "file": "config_v1_generated_config_get_resource_drift_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "config_v1_generated_Config_GetResourceDrift_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": "config_v1_generated_config_get_resource_drift_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.config_v1.ConfigAsyncClient", - "shortName": "ConfigAsyncClient" - }, - "fullName": "google.cloud.config_v1.ConfigAsyncClient.get_resource", - "method": { - "fullName": "google.cloud.config.v1.Config.GetResource", - "service": { - "fullName": "google.cloud.config.v1.Config", - "shortName": "Config" - }, - "shortName": "GetResource" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.config_v1.types.GetResourceRequest" - }, - { - "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.config_v1.types.Resource", - "shortName": "get_resource" - }, - "description": "Sample for GetResource", - "file": "config_v1_generated_config_get_resource_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "config_v1_generated_Config_GetResource_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": "config_v1_generated_config_get_resource_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.config_v1.ConfigClient", - "shortName": "ConfigClient" - }, - "fullName": "google.cloud.config_v1.ConfigClient.get_resource", - "method": { - "fullName": "google.cloud.config.v1.Config.GetResource", - "service": { - "fullName": "google.cloud.config.v1.Config", - "shortName": "Config" - }, - "shortName": "GetResource" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.config_v1.types.GetResourceRequest" - }, - { - "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.config_v1.types.Resource", - "shortName": "get_resource" - }, - "description": "Sample for GetResource", - "file": "config_v1_generated_config_get_resource_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "config_v1_generated_Config_GetResource_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": "config_v1_generated_config_get_resource_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.config_v1.ConfigAsyncClient", - "shortName": "ConfigAsyncClient" - }, - "fullName": "google.cloud.config_v1.ConfigAsyncClient.get_revision", - "method": { - "fullName": "google.cloud.config.v1.Config.GetRevision", - "service": { - "fullName": "google.cloud.config.v1.Config", - "shortName": "Config" - }, - "shortName": "GetRevision" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.config_v1.types.GetRevisionRequest" - }, - { - "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.config_v1.types.Revision", - "shortName": "get_revision" - }, - "description": "Sample for GetRevision", - "file": "config_v1_generated_config_get_revision_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "config_v1_generated_Config_GetRevision_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": "config_v1_generated_config_get_revision_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.config_v1.ConfigClient", - "shortName": "ConfigClient" - }, - "fullName": "google.cloud.config_v1.ConfigClient.get_revision", - "method": { - "fullName": "google.cloud.config.v1.Config.GetRevision", - "service": { - "fullName": "google.cloud.config.v1.Config", - "shortName": "Config" - }, - "shortName": "GetRevision" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.config_v1.types.GetRevisionRequest" - }, - { - "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.config_v1.types.Revision", - "shortName": "get_revision" - }, - "description": "Sample for GetRevision", - "file": "config_v1_generated_config_get_revision_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "config_v1_generated_Config_GetRevision_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": "config_v1_generated_config_get_revision_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.config_v1.ConfigAsyncClient", - "shortName": "ConfigAsyncClient" - }, - "fullName": "google.cloud.config_v1.ConfigAsyncClient.get_terraform_version", - "method": { - "fullName": "google.cloud.config.v1.Config.GetTerraformVersion", - "service": { - "fullName": "google.cloud.config.v1.Config", - "shortName": "Config" - }, - "shortName": "GetTerraformVersion" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.config_v1.types.GetTerraformVersionRequest" - }, - { - "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.config_v1.types.TerraformVersion", - "shortName": "get_terraform_version" - }, - "description": "Sample for GetTerraformVersion", - "file": "config_v1_generated_config_get_terraform_version_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "config_v1_generated_Config_GetTerraformVersion_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": "config_v1_generated_config_get_terraform_version_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.config_v1.ConfigClient", - "shortName": "ConfigClient" - }, - "fullName": "google.cloud.config_v1.ConfigClient.get_terraform_version", - "method": { - "fullName": "google.cloud.config.v1.Config.GetTerraformVersion", - "service": { - "fullName": "google.cloud.config.v1.Config", - "shortName": "Config" - }, - "shortName": "GetTerraformVersion" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.config_v1.types.GetTerraformVersionRequest" - }, - { - "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.config_v1.types.TerraformVersion", - "shortName": "get_terraform_version" - }, - "description": "Sample for GetTerraformVersion", - "file": "config_v1_generated_config_get_terraform_version_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "config_v1_generated_Config_GetTerraformVersion_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": "config_v1_generated_config_get_terraform_version_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.config_v1.ConfigAsyncClient", - "shortName": "ConfigAsyncClient" - }, - "fullName": "google.cloud.config_v1.ConfigAsyncClient.import_statefile", - "method": { - "fullName": "google.cloud.config.v1.Config.ImportStatefile", - "service": { - "fullName": "google.cloud.config.v1.Config", - "shortName": "Config" - }, - "shortName": "ImportStatefile" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.config_v1.types.ImportStatefileRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "lock_id", - "type": "int" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.config_v1.types.Statefile", - "shortName": "import_statefile" - }, - "description": "Sample for ImportStatefile", - "file": "config_v1_generated_config_import_statefile_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "config_v1_generated_Config_ImportStatefile_async", - "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": "config_v1_generated_config_import_statefile_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.config_v1.ConfigClient", - "shortName": "ConfigClient" - }, - "fullName": "google.cloud.config_v1.ConfigClient.import_statefile", - "method": { - "fullName": "google.cloud.config.v1.Config.ImportStatefile", - "service": { - "fullName": "google.cloud.config.v1.Config", - "shortName": "Config" - }, - "shortName": "ImportStatefile" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.config_v1.types.ImportStatefileRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "lock_id", - "type": "int" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.config_v1.types.Statefile", - "shortName": "import_statefile" - }, - "description": "Sample for ImportStatefile", - "file": "config_v1_generated_config_import_statefile_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "config_v1_generated_Config_ImportStatefile_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": "config_v1_generated_config_import_statefile_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.config_v1.ConfigAsyncClient", - "shortName": "ConfigAsyncClient" - }, - "fullName": "google.cloud.config_v1.ConfigAsyncClient.list_deployments", - "method": { - "fullName": "google.cloud.config.v1.Config.ListDeployments", - "service": { - "fullName": "google.cloud.config.v1.Config", - "shortName": "Config" - }, - "shortName": "ListDeployments" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.config_v1.types.ListDeploymentsRequest" - }, - { - "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.config_v1.services.config.pagers.ListDeploymentsAsyncPager", - "shortName": "list_deployments" - }, - "description": "Sample for ListDeployments", - "file": "config_v1_generated_config_list_deployments_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "config_v1_generated_Config_ListDeployments_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": "config_v1_generated_config_list_deployments_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.config_v1.ConfigClient", - "shortName": "ConfigClient" - }, - "fullName": "google.cloud.config_v1.ConfigClient.list_deployments", - "method": { - "fullName": "google.cloud.config.v1.Config.ListDeployments", - "service": { - "fullName": "google.cloud.config.v1.Config", - "shortName": "Config" - }, - "shortName": "ListDeployments" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.config_v1.types.ListDeploymentsRequest" - }, - { - "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.config_v1.services.config.pagers.ListDeploymentsPager", - "shortName": "list_deployments" - }, - "description": "Sample for ListDeployments", - "file": "config_v1_generated_config_list_deployments_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "config_v1_generated_Config_ListDeployments_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": "config_v1_generated_config_list_deployments_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.config_v1.ConfigAsyncClient", - "shortName": "ConfigAsyncClient" - }, - "fullName": "google.cloud.config_v1.ConfigAsyncClient.list_previews", - "method": { - "fullName": "google.cloud.config.v1.Config.ListPreviews", - "service": { - "fullName": "google.cloud.config.v1.Config", - "shortName": "Config" - }, - "shortName": "ListPreviews" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.config_v1.types.ListPreviewsRequest" - }, - { - "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.config_v1.services.config.pagers.ListPreviewsAsyncPager", - "shortName": "list_previews" - }, - "description": "Sample for ListPreviews", - "file": "config_v1_generated_config_list_previews_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "config_v1_generated_Config_ListPreviews_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": "config_v1_generated_config_list_previews_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.config_v1.ConfigClient", - "shortName": "ConfigClient" - }, - "fullName": "google.cloud.config_v1.ConfigClient.list_previews", - "method": { - "fullName": "google.cloud.config.v1.Config.ListPreviews", - "service": { - "fullName": "google.cloud.config.v1.Config", - "shortName": "Config" - }, - "shortName": "ListPreviews" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.config_v1.types.ListPreviewsRequest" - }, - { - "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.config_v1.services.config.pagers.ListPreviewsPager", - "shortName": "list_previews" - }, - "description": "Sample for ListPreviews", - "file": "config_v1_generated_config_list_previews_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "config_v1_generated_Config_ListPreviews_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": "config_v1_generated_config_list_previews_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.config_v1.ConfigAsyncClient", - "shortName": "ConfigAsyncClient" - }, - "fullName": "google.cloud.config_v1.ConfigAsyncClient.list_resource_changes", - "method": { - "fullName": "google.cloud.config.v1.Config.ListResourceChanges", - "service": { - "fullName": "google.cloud.config.v1.Config", - "shortName": "Config" - }, - "shortName": "ListResourceChanges" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.config_v1.types.ListResourceChangesRequest" - }, - { - "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.config_v1.services.config.pagers.ListResourceChangesAsyncPager", - "shortName": "list_resource_changes" - }, - "description": "Sample for ListResourceChanges", - "file": "config_v1_generated_config_list_resource_changes_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "config_v1_generated_Config_ListResourceChanges_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": "config_v1_generated_config_list_resource_changes_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.config_v1.ConfigClient", - "shortName": "ConfigClient" - }, - "fullName": "google.cloud.config_v1.ConfigClient.list_resource_changes", - "method": { - "fullName": "google.cloud.config.v1.Config.ListResourceChanges", - "service": { - "fullName": "google.cloud.config.v1.Config", - "shortName": "Config" - }, - "shortName": "ListResourceChanges" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.config_v1.types.ListResourceChangesRequest" - }, - { - "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.config_v1.services.config.pagers.ListResourceChangesPager", - "shortName": "list_resource_changes" - }, - "description": "Sample for ListResourceChanges", - "file": "config_v1_generated_config_list_resource_changes_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "config_v1_generated_Config_ListResourceChanges_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": "config_v1_generated_config_list_resource_changes_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.config_v1.ConfigAsyncClient", - "shortName": "ConfigAsyncClient" - }, - "fullName": "google.cloud.config_v1.ConfigAsyncClient.list_resource_drifts", - "method": { - "fullName": "google.cloud.config.v1.Config.ListResourceDrifts", - "service": { - "fullName": "google.cloud.config.v1.Config", - "shortName": "Config" - }, - "shortName": "ListResourceDrifts" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.config_v1.types.ListResourceDriftsRequest" - }, - { - "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.config_v1.services.config.pagers.ListResourceDriftsAsyncPager", - "shortName": "list_resource_drifts" - }, - "description": "Sample for ListResourceDrifts", - "file": "config_v1_generated_config_list_resource_drifts_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "config_v1_generated_Config_ListResourceDrifts_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": "config_v1_generated_config_list_resource_drifts_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.config_v1.ConfigClient", - "shortName": "ConfigClient" - }, - "fullName": "google.cloud.config_v1.ConfigClient.list_resource_drifts", - "method": { - "fullName": "google.cloud.config.v1.Config.ListResourceDrifts", - "service": { - "fullName": "google.cloud.config.v1.Config", - "shortName": "Config" - }, - "shortName": "ListResourceDrifts" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.config_v1.types.ListResourceDriftsRequest" - }, - { - "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.config_v1.services.config.pagers.ListResourceDriftsPager", - "shortName": "list_resource_drifts" - }, - "description": "Sample for ListResourceDrifts", - "file": "config_v1_generated_config_list_resource_drifts_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "config_v1_generated_Config_ListResourceDrifts_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": "config_v1_generated_config_list_resource_drifts_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.config_v1.ConfigAsyncClient", - "shortName": "ConfigAsyncClient" - }, - "fullName": "google.cloud.config_v1.ConfigAsyncClient.list_resources", - "method": { - "fullName": "google.cloud.config.v1.Config.ListResources", - "service": { - "fullName": "google.cloud.config.v1.Config", - "shortName": "Config" - }, - "shortName": "ListResources" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.config_v1.types.ListResourcesRequest" - }, - { - "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.config_v1.services.config.pagers.ListResourcesAsyncPager", - "shortName": "list_resources" - }, - "description": "Sample for ListResources", - "file": "config_v1_generated_config_list_resources_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "config_v1_generated_Config_ListResources_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": "config_v1_generated_config_list_resources_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.config_v1.ConfigClient", - "shortName": "ConfigClient" - }, - "fullName": "google.cloud.config_v1.ConfigClient.list_resources", - "method": { - "fullName": "google.cloud.config.v1.Config.ListResources", - "service": { - "fullName": "google.cloud.config.v1.Config", - "shortName": "Config" - }, - "shortName": "ListResources" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.config_v1.types.ListResourcesRequest" - }, - { - "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.config_v1.services.config.pagers.ListResourcesPager", - "shortName": "list_resources" - }, - "description": "Sample for ListResources", - "file": "config_v1_generated_config_list_resources_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "config_v1_generated_Config_ListResources_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": "config_v1_generated_config_list_resources_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.config_v1.ConfigAsyncClient", - "shortName": "ConfigAsyncClient" - }, - "fullName": "google.cloud.config_v1.ConfigAsyncClient.list_revisions", - "method": { - "fullName": "google.cloud.config.v1.Config.ListRevisions", - "service": { - "fullName": "google.cloud.config.v1.Config", - "shortName": "Config" - }, - "shortName": "ListRevisions" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.config_v1.types.ListRevisionsRequest" - }, - { - "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.config_v1.services.config.pagers.ListRevisionsAsyncPager", - "shortName": "list_revisions" - }, - "description": "Sample for ListRevisions", - "file": "config_v1_generated_config_list_revisions_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "config_v1_generated_Config_ListRevisions_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": "config_v1_generated_config_list_revisions_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.config_v1.ConfigClient", - "shortName": "ConfigClient" - }, - "fullName": "google.cloud.config_v1.ConfigClient.list_revisions", - "method": { - "fullName": "google.cloud.config.v1.Config.ListRevisions", - "service": { - "fullName": "google.cloud.config.v1.Config", - "shortName": "Config" - }, - "shortName": "ListRevisions" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.config_v1.types.ListRevisionsRequest" - }, - { - "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.config_v1.services.config.pagers.ListRevisionsPager", - "shortName": "list_revisions" - }, - "description": "Sample for ListRevisions", - "file": "config_v1_generated_config_list_revisions_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "config_v1_generated_Config_ListRevisions_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": "config_v1_generated_config_list_revisions_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.config_v1.ConfigAsyncClient", - "shortName": "ConfigAsyncClient" - }, - "fullName": "google.cloud.config_v1.ConfigAsyncClient.list_terraform_versions", - "method": { - "fullName": "google.cloud.config.v1.Config.ListTerraformVersions", - "service": { - "fullName": "google.cloud.config.v1.Config", - "shortName": "Config" - }, - "shortName": "ListTerraformVersions" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.config_v1.types.ListTerraformVersionsRequest" - }, - { - "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.config_v1.services.config.pagers.ListTerraformVersionsAsyncPager", - "shortName": "list_terraform_versions" - }, - "description": "Sample for ListTerraformVersions", - "file": "config_v1_generated_config_list_terraform_versions_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "config_v1_generated_Config_ListTerraformVersions_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": "config_v1_generated_config_list_terraform_versions_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.config_v1.ConfigClient", - "shortName": "ConfigClient" - }, - "fullName": "google.cloud.config_v1.ConfigClient.list_terraform_versions", - "method": { - "fullName": "google.cloud.config.v1.Config.ListTerraformVersions", - "service": { - "fullName": "google.cloud.config.v1.Config", - "shortName": "Config" - }, - "shortName": "ListTerraformVersions" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.config_v1.types.ListTerraformVersionsRequest" - }, - { - "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.config_v1.services.config.pagers.ListTerraformVersionsPager", - "shortName": "list_terraform_versions" - }, - "description": "Sample for ListTerraformVersions", - "file": "config_v1_generated_config_list_terraform_versions_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "config_v1_generated_Config_ListTerraformVersions_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": "config_v1_generated_config_list_terraform_versions_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.config_v1.ConfigAsyncClient", - "shortName": "ConfigAsyncClient" - }, - "fullName": "google.cloud.config_v1.ConfigAsyncClient.lock_deployment", - "method": { - "fullName": "google.cloud.config.v1.Config.LockDeployment", - "service": { - "fullName": "google.cloud.config.v1.Config", - "shortName": "Config" - }, - "shortName": "LockDeployment" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.config_v1.types.LockDeploymentRequest" - }, - { - "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": "lock_deployment" - }, - "description": "Sample for LockDeployment", - "file": "config_v1_generated_config_lock_deployment_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "config_v1_generated_Config_LockDeployment_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": "config_v1_generated_config_lock_deployment_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.config_v1.ConfigClient", - "shortName": "ConfigClient" - }, - "fullName": "google.cloud.config_v1.ConfigClient.lock_deployment", - "method": { - "fullName": "google.cloud.config.v1.Config.LockDeployment", - "service": { - "fullName": "google.cloud.config.v1.Config", - "shortName": "Config" - }, - "shortName": "LockDeployment" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.config_v1.types.LockDeploymentRequest" - }, - { - "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": "lock_deployment" - }, - "description": "Sample for LockDeployment", - "file": "config_v1_generated_config_lock_deployment_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "config_v1_generated_Config_LockDeployment_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": "config_v1_generated_config_lock_deployment_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.config_v1.ConfigAsyncClient", - "shortName": "ConfigAsyncClient" - }, - "fullName": "google.cloud.config_v1.ConfigAsyncClient.unlock_deployment", - "method": { - "fullName": "google.cloud.config.v1.Config.UnlockDeployment", - "service": { - "fullName": "google.cloud.config.v1.Config", - "shortName": "Config" - }, - "shortName": "UnlockDeployment" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.config_v1.types.UnlockDeploymentRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "lock_id", - "type": "int" - }, - { - "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": "unlock_deployment" - }, - "description": "Sample for UnlockDeployment", - "file": "config_v1_generated_config_unlock_deployment_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "config_v1_generated_Config_UnlockDeployment_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": "config_v1_generated_config_unlock_deployment_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.config_v1.ConfigClient", - "shortName": "ConfigClient" - }, - "fullName": "google.cloud.config_v1.ConfigClient.unlock_deployment", - "method": { - "fullName": "google.cloud.config.v1.Config.UnlockDeployment", - "service": { - "fullName": "google.cloud.config.v1.Config", - "shortName": "Config" - }, - "shortName": "UnlockDeployment" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.config_v1.types.UnlockDeploymentRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "lock_id", - "type": "int" - }, - { - "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": "unlock_deployment" - }, - "description": "Sample for UnlockDeployment", - "file": "config_v1_generated_config_unlock_deployment_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "config_v1_generated_Config_UnlockDeployment_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": "config_v1_generated_config_unlock_deployment_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.config_v1.ConfigAsyncClient", - "shortName": "ConfigAsyncClient" - }, - "fullName": "google.cloud.config_v1.ConfigAsyncClient.update_deployment", - "method": { - "fullName": "google.cloud.config.v1.Config.UpdateDeployment", - "service": { - "fullName": "google.cloud.config.v1.Config", - "shortName": "Config" - }, - "shortName": "UpdateDeployment" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.config_v1.types.UpdateDeploymentRequest" - }, - { - "name": "deployment", - "type": "google.cloud.config_v1.types.Deployment" - }, - { - "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_deployment" - }, - "description": "Sample for UpdateDeployment", - "file": "config_v1_generated_config_update_deployment_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "config_v1_generated_Config_UpdateDeployment_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": "config_v1_generated_config_update_deployment_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.config_v1.ConfigClient", - "shortName": "ConfigClient" - }, - "fullName": "google.cloud.config_v1.ConfigClient.update_deployment", - "method": { - "fullName": "google.cloud.config.v1.Config.UpdateDeployment", - "service": { - "fullName": "google.cloud.config.v1.Config", - "shortName": "Config" - }, - "shortName": "UpdateDeployment" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.config_v1.types.UpdateDeploymentRequest" - }, - { - "name": "deployment", - "type": "google.cloud.config_v1.types.Deployment" - }, - { - "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_deployment" - }, - "description": "Sample for UpdateDeployment", - "file": "config_v1_generated_config_update_deployment_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "config_v1_generated_Config_UpdateDeployment_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": "config_v1_generated_config_update_deployment_sync.py" - } - ] -} diff --git a/owl-bot-staging/google-cloud-config/v1/scripts/fixup_config_v1_keywords.py b/owl-bot-staging/google-cloud-config/v1/scripts/fixup_config_v1_keywords.py deleted file mode 100644 index c3a279472125..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/scripts/fixup_config_v1_keywords.py +++ /dev/null @@ -1,202 +0,0 @@ -#! /usr/bin/env python3 -# -*- 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. -# -import argparse -import os -import libcst as cst -import pathlib -import sys -from typing import (Any, Callable, Dict, List, Sequence, Tuple) - - -def partition( - predicate: Callable[[Any], bool], - iterator: Sequence[Any] -) -> Tuple[List[Any], List[Any]]: - """A stable, out-of-place partition.""" - results = ([], []) - - for i in iterator: - results[int(predicate(i))].append(i) - - # Returns trueList, falseList - return results[1], results[0] - - -class configCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'create_deployment': ('parent', 'deployment_id', 'deployment', 'request_id', ), - 'create_preview': ('parent', 'preview', 'preview_id', 'request_id', ), - 'delete_deployment': ('name', 'request_id', 'force', 'delete_policy', ), - 'delete_preview': ('name', 'request_id', ), - 'delete_statefile': ('name', 'lock_id', ), - 'export_deployment_statefile': ('parent', 'draft', ), - 'export_lock_info': ('name', ), - 'export_preview_result': ('parent', ), - 'export_revision_statefile': ('parent', ), - 'get_deployment': ('name', ), - 'get_preview': ('name', ), - 'get_resource': ('name', ), - 'get_resource_change': ('name', ), - 'get_resource_drift': ('name', ), - 'get_revision': ('name', ), - 'get_terraform_version': ('name', ), - 'import_statefile': ('parent', 'lock_id', 'skip_draft', ), - 'list_deployments': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), - 'list_previews': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), - 'list_resource_changes': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), - 'list_resource_drifts': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), - 'list_resources': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), - 'list_revisions': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), - 'list_terraform_versions': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), - 'lock_deployment': ('name', ), - 'unlock_deployment': ('name', 'lock_id', ), - 'update_deployment': ('deployment', 'update_mask', 'request_id', ), - } - - def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: - try: - key = original.func.attr.value - kword_params = self.METHOD_TO_PARAMS[key] - except (AttributeError, KeyError): - # Either not a method from the API or too convoluted to be sure. - return updated - - # If the existing code is valid, keyword args come after positional args. - # Therefore, all positional args must map to the first parameters. - args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) - if any(k.keyword.value == "request" for k in kwargs): - # We've already fixed this file, don't fix it again. - return updated - - kwargs, ctrl_kwargs = partition( - lambda a: a.keyword.value not in self.CTRL_PARAMS, - kwargs - ) - - args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] - ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) - for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) - - request_arg = cst.Arg( - value=cst.Dict([ - cst.DictElement( - cst.SimpleString("'{}'".format(name)), -cst.Element(value=arg.value) - ) - # Note: the args + kwargs looks silly, but keep in mind that - # the control parameters had to be stripped out, and that - # those could have been passed positionally or by keyword. - for name, arg in zip(kword_params, args + kwargs)]), - keyword=cst.Name("request") - ) - - return updated.with_changes( - args=[request_arg] + ctrl_kwargs - ) - - -def fix_files( - in_dir: pathlib.Path, - out_dir: pathlib.Path, - *, - transformer=configCallTransformer(), -): - """Duplicate the input dir to the output dir, fixing file method calls. - - Preconditions: - * in_dir is a real directory - * out_dir is a real, empty directory - """ - pyfile_gen = ( - pathlib.Path(os.path.join(root, f)) - for root, _, files in os.walk(in_dir) - for f in files if os.path.splitext(f)[1] == ".py" - ) - - for fpath in pyfile_gen: - with open(fpath, 'r') as f: - src = f.read() - - # Parse the code and insert method call fixes. - tree = cst.parse_module(src) - updated = tree.visit(transformer) - - # Create the path and directory structure for the new file. - updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) - updated_path.parent.mkdir(parents=True, exist_ok=True) - - # Generate the updated source file at the corresponding path. - with open(updated_path, 'w') as f: - f.write(updated.code) - - -if __name__ == '__main__': - parser = argparse.ArgumentParser( - description="""Fix up source that uses the config client library. - -The existing sources are NOT overwritten but are copied to output_dir with changes made. - -Note: This tool operates at a best-effort level at converting positional - parameters in client method calls to keyword based parameters. - Cases where it WILL FAIL include - A) * or ** expansion in a method call. - B) Calls via function or method alias (includes free function calls) - C) Indirect or dispatched calls (e.g. the method is looked up dynamically) - - These all constitute false negatives. The tool will also detect false - positives when an API method shares a name with another method. -""") - parser.add_argument( - '-d', - '--input-directory', - required=True, - dest='input_dir', - help='the input directory to walk for python files to fix up', - ) - parser.add_argument( - '-o', - '--output-directory', - required=True, - dest='output_dir', - help='the directory to output files fixed via un-flattening', - ) - args = parser.parse_args() - input_dir = pathlib.Path(args.input_dir) - output_dir = pathlib.Path(args.output_dir) - if not input_dir.is_dir(): - print( - f"input directory '{input_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if not output_dir.is_dir(): - print( - f"output directory '{output_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if os.listdir(output_dir): - print( - f"output directory '{output_dir}' is not empty", - file=sys.stderr, - ) - sys.exit(-1) - - fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/google-cloud-config/v1/setup.py b/owl-bot-staging/google-cloud-config/v1/setup.py deleted file mode 100644 index 07c589a6f969..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/setup.py +++ /dev/null @@ -1,99 +0,0 @@ -# -*- 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. -# -import io -import os -import re - -import setuptools # type: ignore - -package_root = os.path.abspath(os.path.dirname(__file__)) - -name = 'google-cloud-config' - - -description = "Google Cloud Config API client library" - -version = None - -with open(os.path.join(package_root, 'google/cloud/config/gapic_version.py')) as fp: - version_candidates = re.findall(r"(?<=\")\d+.\d+.\d+(?=\")", fp.read()) - assert (len(version_candidates) == 1) - version = version_candidates[0] - -if version[0] == "0": - release_status = "Development Status :: 4 - Beta" -else: - release_status = "Development Status :: 5 - Production/Stable" - -dependencies = [ - "google-api-core[grpc] >= 1.34.1, <3.0.0,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - # Exclude incompatible versions of `google-auth` - # See https://github.com/googleapis/google-cloud-python/issues/12364 - "google-auth >= 2.14.1, <3.0.0,!=2.24.0,!=2.25.0", - "proto-plus >= 1.22.3, <2.0.0", - "proto-plus >= 1.25.0, <2.0.0; python_version >= '3.13'", - "protobuf>=3.20.2,<7.0.0,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", - "grpc-google-iam-v1 >= 0.14.0, <1.0.0", -] -extras = { -} -url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-config" - -package_root = os.path.abspath(os.path.dirname(__file__)) - -readme_filename = os.path.join(package_root, "README.rst") -with io.open(readme_filename, encoding="utf-8") as readme_file: - readme = readme_file.read() - -packages = [ - package - for package in setuptools.find_namespace_packages() - if package.startswith("google") -] - -setuptools.setup( - name=name, - version=version, - description=description, - long_description=readme, - author="Google LLC", - author_email="googleapis-packages@google.com", - license="Apache 2.0", - url=url, - classifiers=[ - release_status, - "Intended Audience :: Developers", - "License :: OSI Approved :: Apache Software License", - "Programming Language :: Python", - "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.7", - "Programming Language :: Python :: 3.8", - "Programming Language :: Python :: 3.9", - "Programming Language :: Python :: 3.10", - "Programming Language :: Python :: 3.11", - "Programming Language :: Python :: 3.12", - "Programming Language :: Python :: 3.13", - "Operating System :: OS Independent", - "Topic :: Internet", - ], - platforms="Posix; MacOS X; Windows", - packages=packages, - python_requires=">=3.7", - install_requires=dependencies, - extras_require=extras, - include_package_data=True, - zip_safe=False, -) diff --git a/owl-bot-staging/google-cloud-config/v1/testing/constraints-3.10.txt b/owl-bot-staging/google-cloud-config/v1/testing/constraints-3.10.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/testing/constraints-3.10.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-config/v1/testing/constraints-3.11.txt b/owl-bot-staging/google-cloud-config/v1/testing/constraints-3.11.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/testing/constraints-3.11.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-config/v1/testing/constraints-3.12.txt b/owl-bot-staging/google-cloud-config/v1/testing/constraints-3.12.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/testing/constraints-3.12.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-config/v1/testing/constraints-3.13.txt b/owl-bot-staging/google-cloud-config/v1/testing/constraints-3.13.txt deleted file mode 100644 index 2010e549cceb..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/testing/constraints-3.13.txt +++ /dev/null @@ -1,12 +0,0 @@ -# We use the constraints file for the latest Python version -# (currently this file) to check that the latest -# major versions of dependencies are supported in setup.py. -# List all library dependencies and extras in this file. -# Require the latest major version be installed for each dependency. -# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0", -# Then this file should have google-cloud-foo>=1 -google-api-core>=2 -google-auth>=2 -proto-plus>=1 -protobuf>=6 -grpc-google-iam-v1>=0 diff --git a/owl-bot-staging/google-cloud-config/v1/testing/constraints-3.7.txt b/owl-bot-staging/google-cloud-config/v1/testing/constraints-3.7.txt deleted file mode 100644 index 56affbd9bd75..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/testing/constraints-3.7.txt +++ /dev/null @@ -1,11 +0,0 @@ -# This constraints file is used to check that lower bounds -# are correct in setup.py -# List all library dependencies and extras in this file. -# Pin the version to the lower bound. -# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0", -# Then this file should have google-cloud-foo==1.14.0 -google-api-core==1.34.1 -google-auth==2.14.1 -proto-plus==1.22.3 -protobuf==3.20.2 -grpc-google-iam-v1==0.14.0 diff --git a/owl-bot-staging/google-cloud-config/v1/testing/constraints-3.8.txt b/owl-bot-staging/google-cloud-config/v1/testing/constraints-3.8.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/testing/constraints-3.8.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-config/v1/testing/constraints-3.9.txt b/owl-bot-staging/google-cloud-config/v1/testing/constraints-3.9.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/testing/constraints-3.9.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- coding: utf-8 -*- -# This constraints file is required for unit tests. -# List all library dependencies and extras in this file. -google-api-core -proto-plus -protobuf -grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-config/v1/tests/__init__.py b/owl-bot-staging/google-cloud-config/v1/tests/__init__.py deleted file mode 100644 index 191773d5572d..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/tests/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- 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. -# diff --git a/owl-bot-staging/google-cloud-config/v1/tests/unit/__init__.py b/owl-bot-staging/google-cloud-config/v1/tests/unit/__init__.py deleted file mode 100644 index 191773d5572d..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/tests/unit/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- 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. -# diff --git a/owl-bot-staging/google-cloud-config/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/google-cloud-config/v1/tests/unit/gapic/__init__.py deleted file mode 100644 index 191773d5572d..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- 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. -# diff --git a/owl-bot-staging/google-cloud-config/v1/tests/unit/gapic/config_v1/__init__.py b/owl-bot-staging/google-cloud-config/v1/tests/unit/gapic/config_v1/__init__.py deleted file mode 100644 index 191773d5572d..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/tests/unit/gapic/config_v1/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- 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. -# diff --git a/owl-bot-staging/google-cloud-config/v1/tests/unit/gapic/config_v1/test_config.py b/owl-bot-staging/google-cloud-config/v1/tests/unit/gapic/config_v1/test_config.py deleted file mode 100644 index 6beae688408a..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/tests/unit/gapic/config_v1/test_config.py +++ /dev/null @@ -1,23350 +0,0 @@ -# -*- 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. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable, AsyncIterable -from google.protobuf import json_format -import json -import math -import pytest -from google.api_core import api_core_version -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -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 - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import future -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import operation -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.api_core import path_template -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.config_v1.services.config import ConfigAsyncClient -from google.cloud.config_v1.services.config import ConfigClient -from google.cloud.config_v1.services.config import pagers -from google.cloud.config_v1.services.config import transports -from google.cloud.config_v1.types import config -from google.cloud.location import locations_pb2 -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import options_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.oauth2 import service_account -from google.protobuf import any_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore -import google.auth - - - -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) - - -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 - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert ConfigClient._get_default_mtls_endpoint(None) is None - assert ConfigClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert ConfigClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert ConfigClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert ConfigClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert ConfigClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - -def test__read_environment_variables(): - assert ConfigClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert ConfigClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert ConfigClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - ConfigClient._read_environment_variables() - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - assert ConfigClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert ConfigClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert ConfigClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - ConfigClient._read_environment_variables() - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - - with mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"}): - assert ConfigClient._read_environment_variables() == (False, "auto", "foo.com") - -def test__get_client_cert_source(): - mock_provided_cert_source = mock.Mock() - mock_default_cert_source = mock.Mock() - - assert ConfigClient._get_client_cert_source(None, False) is None - assert ConfigClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert ConfigClient._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 ConfigClient._get_client_cert_source(None, True) is mock_default_cert_source - assert ConfigClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(ConfigClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ConfigClient)) -@mock.patch.object(ConfigAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ConfigAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = ConfigClient._DEFAULT_UNIVERSE - default_endpoint = ConfigClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = ConfigClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert ConfigClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert ConfigClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == ConfigClient.DEFAULT_MTLS_ENDPOINT - assert ConfigClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert ConfigClient._get_api_endpoint(None, None, default_universe, "always") == ConfigClient.DEFAULT_MTLS_ENDPOINT - assert ConfigClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == ConfigClient.DEFAULT_MTLS_ENDPOINT - assert ConfigClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert ConfigClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - ConfigClient._get_api_endpoint(None, mock_client_cert_source, mock_universe, "auto") - assert str(excinfo.value) == "mTLS is not supported in any universe other than googleapis.com." - - -def test__get_universe_domain(): - client_universe_domain = "foo.com" - universe_domain_env = "bar.com" - - assert ConfigClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert ConfigClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert ConfigClient._get_universe_domain(None, None) == ConfigClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - ConfigClient._get_universe_domain("", None) - assert str(excinfo.value) == "Universe Domain cannot be an empty string." - -@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 = ConfigClient(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 = ConfigClient(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", [ - (ConfigClient, "grpc"), - (ConfigAsyncClient, "grpc_asyncio"), - (ConfigClient, "rest"), -]) -def test_config_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 == ( - 'config.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://config.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.ConfigGrpcTransport, "grpc"), - (transports.ConfigGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.ConfigRestTransport, "rest"), -]) -def test_config_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", [ - (ConfigClient, "grpc"), - (ConfigAsyncClient, "grpc_asyncio"), - (ConfigClient, "rest"), -]) -def test_config_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 == ( - 'config.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://config.googleapis.com' - ) - - -def test_config_client_get_transport_class(): - transport = ConfigClient.get_transport_class() - available_transports = [ - transports.ConfigGrpcTransport, - transports.ConfigRestTransport, - ] - assert transport in available_transports - - transport = ConfigClient.get_transport_class("grpc") - assert transport == transports.ConfigGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ConfigClient, transports.ConfigGrpcTransport, "grpc"), - (ConfigAsyncClient, transports.ConfigGrpcAsyncIOTransport, "grpc_asyncio"), - (ConfigClient, transports.ConfigRestTransport, "rest"), -]) -@mock.patch.object(ConfigClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ConfigClient)) -@mock.patch.object(ConfigAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ConfigAsyncClient)) -def test_config_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(ConfigClient, '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(ConfigClient, '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 GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - client = client_class(transport=transport_name) - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - - # 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", [ - (ConfigClient, transports.ConfigGrpcTransport, "grpc", "true"), - (ConfigAsyncClient, transports.ConfigGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (ConfigClient, transports.ConfigGrpcTransport, "grpc", "false"), - (ConfigAsyncClient, transports.ConfigGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (ConfigClient, transports.ConfigRestTransport, "rest", "true"), - (ConfigClient, transports.ConfigRestTransport, "rest", "false"), -]) -@mock.patch.object(ConfigClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ConfigClient)) -@mock.patch.object(ConfigAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ConfigAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_config_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", [ - ConfigClient, ConfigAsyncClient -]) -@mock.patch.object(ConfigClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConfigClient)) -@mock.patch.object(ConfigAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ConfigAsyncClient)) -def test_config_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_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`" - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - client_class.get_mtls_endpoint_and_cert_source() - - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - -@pytest.mark.parametrize("client_class", [ - ConfigClient, ConfigAsyncClient -]) -@mock.patch.object(ConfigClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ConfigClient)) -@mock.patch.object(ConfigAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ConfigAsyncClient)) -def test_config_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = ConfigClient._DEFAULT_UNIVERSE - default_endpoint = ConfigClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = ConfigClient._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", [ - (ConfigClient, transports.ConfigGrpcTransport, "grpc"), - (ConfigAsyncClient, transports.ConfigGrpcAsyncIOTransport, "grpc_asyncio"), - (ConfigClient, transports.ConfigRestTransport, "rest"), -]) -def test_config_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", [ - (ConfigClient, transports.ConfigGrpcTransport, "grpc", grpc_helpers), - (ConfigAsyncClient, transports.ConfigGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (ConfigClient, transports.ConfigRestTransport, "rest", None), -]) -def test_config_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_config_client_client_options_from_dict(): - with mock.patch('google.cloud.config_v1.services.config.transports.ConfigGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = ConfigClient( - 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", [ - (ConfigClient, transports.ConfigGrpcTransport, "grpc", grpc_helpers), - (ConfigAsyncClient, transports.ConfigGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_config_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( - "config.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="config.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - config.ListDeploymentsRequest, - dict, -]) -def test_list_deployments(request_type, transport: str = 'grpc'): - client = ConfigClient( - 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_deployments), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = config.ListDeploymentsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - ) - response = client.list_deployments(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = config.ListDeploymentsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListDeploymentsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -def test_list_deployments_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 = ConfigClient( - 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 = config.ListDeploymentsRequest( - 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_deployments), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_deployments(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == config.ListDeploymentsRequest( - parent='parent_value', - page_token='page_token_value', - filter='filter_value', - order_by='order_by_value', - ) - -def test_list_deployments_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create 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 = ConfigClient( - 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_deployments in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_deployments] = mock_rpc - request = {} - client.list_deployments(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_deployments(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_deployments_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 = ConfigAsyncClient( - 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_deployments 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_deployments] = mock_rpc - - request = {} - await client.list_deployments(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_deployments(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_deployments_async(transport: str = 'grpc_asyncio', request_type=config.ListDeploymentsRequest): - client = ConfigAsyncClient( - 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_deployments), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(config.ListDeploymentsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - )) - response = await client.list_deployments(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = config.ListDeploymentsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListDeploymentsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -@pytest.mark.asyncio -async def test_list_deployments_async_from_dict(): - await test_list_deployments_async(request_type=dict) - -def test_list_deployments_field_headers(): - client = ConfigClient( - 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 = config.ListDeploymentsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_deployments), - '__call__') as call: - call.return_value = config.ListDeploymentsResponse() - client.list_deployments(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_deployments_field_headers_async(): - client = ConfigAsyncClient( - 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 = config.ListDeploymentsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_deployments), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.ListDeploymentsResponse()) - await client.list_deployments(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_deployments_flattened(): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_deployments), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = config.ListDeploymentsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_deployments( - 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_deployments_flattened_error(): - client = ConfigClient( - 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_deployments( - config.ListDeploymentsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_deployments_flattened_async(): - client = ConfigAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_deployments), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = config.ListDeploymentsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.ListDeploymentsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_deployments( - 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_deployments_flattened_error_async(): - client = ConfigAsyncClient( - 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_deployments( - config.ListDeploymentsRequest(), - parent='parent_value', - ) - - -def test_list_deployments_pager(transport_name: str = "grpc"): - client = ConfigClient( - 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_deployments), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - config.ListDeploymentsResponse( - deployments=[ - config.Deployment(), - config.Deployment(), - config.Deployment(), - ], - next_page_token='abc', - ), - config.ListDeploymentsResponse( - deployments=[], - next_page_token='def', - ), - config.ListDeploymentsResponse( - deployments=[ - config.Deployment(), - ], - next_page_token='ghi', - ), - config.ListDeploymentsResponse( - deployments=[ - config.Deployment(), - config.Deployment(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_deployments(request={}, retry=retry, timeout=timeout) - - assert pager._metadata == expected_metadata - assert pager._retry == retry - assert pager._timeout == timeout - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, config.Deployment) - for i in results) -def test_list_deployments_pages(transport_name: str = "grpc"): - client = ConfigClient( - 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_deployments), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - config.ListDeploymentsResponse( - deployments=[ - config.Deployment(), - config.Deployment(), - config.Deployment(), - ], - next_page_token='abc', - ), - config.ListDeploymentsResponse( - deployments=[], - next_page_token='def', - ), - config.ListDeploymentsResponse( - deployments=[ - config.Deployment(), - ], - next_page_token='ghi', - ), - config.ListDeploymentsResponse( - deployments=[ - config.Deployment(), - config.Deployment(), - ], - ), - RuntimeError, - ) - pages = list(client.list_deployments(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_deployments_async_pager(): - client = ConfigAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_deployments), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - config.ListDeploymentsResponse( - deployments=[ - config.Deployment(), - config.Deployment(), - config.Deployment(), - ], - next_page_token='abc', - ), - config.ListDeploymentsResponse( - deployments=[], - next_page_token='def', - ), - config.ListDeploymentsResponse( - deployments=[ - config.Deployment(), - ], - next_page_token='ghi', - ), - config.ListDeploymentsResponse( - deployments=[ - config.Deployment(), - config.Deployment(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_deployments(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, config.Deployment) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_deployments_async_pages(): - client = ConfigAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_deployments), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - config.ListDeploymentsResponse( - deployments=[ - config.Deployment(), - config.Deployment(), - config.Deployment(), - ], - next_page_token='abc', - ), - config.ListDeploymentsResponse( - deployments=[], - next_page_token='def', - ), - config.ListDeploymentsResponse( - deployments=[ - config.Deployment(), - ], - next_page_token='ghi', - ), - config.ListDeploymentsResponse( - deployments=[ - config.Deployment(), - config.Deployment(), - ], - ), - RuntimeError, - ) - pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.list_deployments(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", [ - config.GetDeploymentRequest, - dict, -]) -def test_get_deployment(request_type, transport: str = 'grpc'): - client = ConfigClient( - 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_deployment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = config.Deployment( - name='name_value', - state=config.Deployment.State.CREATING, - latest_revision='latest_revision_value', - state_detail='state_detail_value', - error_code=config.Deployment.ErrorCode.REVISION_FAILED, - delete_build='delete_build_value', - delete_logs='delete_logs_value', - error_logs='error_logs_value', - artifacts_gcs_bucket='artifacts_gcs_bucket_value', - service_account='service_account_value', - import_existing_resources=True, - worker_pool='worker_pool_value', - lock_state=config.Deployment.LockState.LOCKED, - tf_version_constraint='tf_version_constraint_value', - tf_version='tf_version_value', - quota_validation=config.QuotaValidation.ENABLED, - ) - response = client.get_deployment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = config.GetDeploymentRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, config.Deployment) - assert response.name == 'name_value' - assert response.state == config.Deployment.State.CREATING - assert response.latest_revision == 'latest_revision_value' - assert response.state_detail == 'state_detail_value' - assert response.error_code == config.Deployment.ErrorCode.REVISION_FAILED - assert response.delete_build == 'delete_build_value' - assert response.delete_logs == 'delete_logs_value' - assert response.error_logs == 'error_logs_value' - assert response.artifacts_gcs_bucket == 'artifacts_gcs_bucket_value' - assert response.service_account == 'service_account_value' - assert response.import_existing_resources is True - assert response.worker_pool == 'worker_pool_value' - assert response.lock_state == config.Deployment.LockState.LOCKED - assert response.tf_version_constraint == 'tf_version_constraint_value' - assert response.tf_version == 'tf_version_value' - assert response.quota_validation == config.QuotaValidation.ENABLED - - -def test_get_deployment_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 = ConfigClient( - 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 = config.GetDeploymentRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_deployment), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_deployment(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == config.GetDeploymentRequest( - name='name_value', - ) - -def test_get_deployment_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create 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 = ConfigClient( - 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_deployment in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_deployment] = mock_rpc - request = {} - client.get_deployment(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_deployment(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_deployment_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 = ConfigAsyncClient( - 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_deployment 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_deployment] = mock_rpc - - request = {} - await client.get_deployment(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_deployment(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_deployment_async(transport: str = 'grpc_asyncio', request_type=config.GetDeploymentRequest): - client = ConfigAsyncClient( - 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_deployment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(config.Deployment( - name='name_value', - state=config.Deployment.State.CREATING, - latest_revision='latest_revision_value', - state_detail='state_detail_value', - error_code=config.Deployment.ErrorCode.REVISION_FAILED, - delete_build='delete_build_value', - delete_logs='delete_logs_value', - error_logs='error_logs_value', - artifacts_gcs_bucket='artifacts_gcs_bucket_value', - service_account='service_account_value', - import_existing_resources=True, - worker_pool='worker_pool_value', - lock_state=config.Deployment.LockState.LOCKED, - tf_version_constraint='tf_version_constraint_value', - tf_version='tf_version_value', - quota_validation=config.QuotaValidation.ENABLED, - )) - response = await client.get_deployment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = config.GetDeploymentRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, config.Deployment) - assert response.name == 'name_value' - assert response.state == config.Deployment.State.CREATING - assert response.latest_revision == 'latest_revision_value' - assert response.state_detail == 'state_detail_value' - assert response.error_code == config.Deployment.ErrorCode.REVISION_FAILED - assert response.delete_build == 'delete_build_value' - assert response.delete_logs == 'delete_logs_value' - assert response.error_logs == 'error_logs_value' - assert response.artifacts_gcs_bucket == 'artifacts_gcs_bucket_value' - assert response.service_account == 'service_account_value' - assert response.import_existing_resources is True - assert response.worker_pool == 'worker_pool_value' - assert response.lock_state == config.Deployment.LockState.LOCKED - assert response.tf_version_constraint == 'tf_version_constraint_value' - assert response.tf_version == 'tf_version_value' - assert response.quota_validation == config.QuotaValidation.ENABLED - - -@pytest.mark.asyncio -async def test_get_deployment_async_from_dict(): - await test_get_deployment_async(request_type=dict) - -def test_get_deployment_field_headers(): - client = ConfigClient( - 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 = config.GetDeploymentRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_deployment), - '__call__') as call: - call.return_value = config.Deployment() - client.get_deployment(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_deployment_field_headers_async(): - client = ConfigAsyncClient( - 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 = config.GetDeploymentRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_deployment), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.Deployment()) - await client.get_deployment(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_deployment_flattened(): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_deployment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = config.Deployment() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_deployment( - 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_deployment_flattened_error(): - client = ConfigClient( - 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_deployment( - config.GetDeploymentRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_deployment_flattened_async(): - client = ConfigAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_deployment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = config.Deployment() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.Deployment()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_deployment( - 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_deployment_flattened_error_async(): - client = ConfigAsyncClient( - 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_deployment( - config.GetDeploymentRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - config.CreateDeploymentRequest, - dict, -]) -def test_create_deployment(request_type, transport: str = 'grpc'): - client = ConfigClient( - 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_deployment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.create_deployment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = config.CreateDeploymentRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_create_deployment_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 = ConfigClient( - 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 = config.CreateDeploymentRequest( - parent='parent_value', - deployment_id='deployment_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_deployment), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_deployment(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == config.CreateDeploymentRequest( - parent='parent_value', - deployment_id='deployment_id_value', - request_id='request_id_value', - ) - -def test_create_deployment_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create 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 = ConfigClient( - 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_deployment in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_deployment] = mock_rpc - request = {} - client.create_deployment(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_deployment(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_deployment_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 = ConfigAsyncClient( - 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_deployment 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_deployment] = mock_rpc - - request = {} - await client.create_deployment(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_deployment(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_deployment_async(transport: str = 'grpc_asyncio', request_type=config.CreateDeploymentRequest): - client = ConfigAsyncClient( - 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_deployment), - '__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_deployment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = config.CreateDeploymentRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_create_deployment_async_from_dict(): - await test_create_deployment_async(request_type=dict) - -def test_create_deployment_field_headers(): - client = ConfigClient( - 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 = config.CreateDeploymentRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_deployment), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_deployment(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_deployment_field_headers_async(): - client = ConfigAsyncClient( - 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 = config.CreateDeploymentRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_deployment), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.create_deployment(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_deployment_flattened(): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_deployment), - '__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_deployment( - parent='parent_value', - deployment=config.Deployment(terraform_blueprint=config.TerraformBlueprint(gcs_source='gcs_source_value')), - deployment_id='deployment_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].deployment - mock_val = config.Deployment(terraform_blueprint=config.TerraformBlueprint(gcs_source='gcs_source_value')) - assert arg == mock_val - arg = args[0].deployment_id - mock_val = 'deployment_id_value' - assert arg == mock_val - - -def test_create_deployment_flattened_error(): - client = ConfigClient( - 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_deployment( - config.CreateDeploymentRequest(), - parent='parent_value', - deployment=config.Deployment(terraform_blueprint=config.TerraformBlueprint(gcs_source='gcs_source_value')), - deployment_id='deployment_id_value', - ) - -@pytest.mark.asyncio -async def test_create_deployment_flattened_async(): - client = ConfigAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_deployment), - '__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_deployment( - parent='parent_value', - deployment=config.Deployment(terraform_blueprint=config.TerraformBlueprint(gcs_source='gcs_source_value')), - deployment_id='deployment_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].deployment - mock_val = config.Deployment(terraform_blueprint=config.TerraformBlueprint(gcs_source='gcs_source_value')) - assert arg == mock_val - arg = args[0].deployment_id - mock_val = 'deployment_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_deployment_flattened_error_async(): - client = ConfigAsyncClient( - 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_deployment( - config.CreateDeploymentRequest(), - parent='parent_value', - deployment=config.Deployment(terraform_blueprint=config.TerraformBlueprint(gcs_source='gcs_source_value')), - deployment_id='deployment_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - config.UpdateDeploymentRequest, - dict, -]) -def test_update_deployment(request_type, transport: str = 'grpc'): - client = ConfigClient( - 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_deployment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.update_deployment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = config.UpdateDeploymentRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_update_deployment_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 = ConfigClient( - 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 = config.UpdateDeploymentRequest( - request_id='request_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_deployment), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_deployment(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == config.UpdateDeploymentRequest( - request_id='request_id_value', - ) - -def test_update_deployment_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create 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 = ConfigClient( - 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_deployment in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_deployment] = mock_rpc - request = {} - client.update_deployment(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_deployment(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_deployment_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 = ConfigAsyncClient( - 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_deployment 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_deployment] = mock_rpc - - request = {} - await client.update_deployment(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_deployment(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_deployment_async(transport: str = 'grpc_asyncio', request_type=config.UpdateDeploymentRequest): - client = ConfigAsyncClient( - 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_deployment), - '__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_deployment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = config.UpdateDeploymentRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_update_deployment_async_from_dict(): - await test_update_deployment_async(request_type=dict) - -def test_update_deployment_field_headers(): - client = ConfigClient( - 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 = config.UpdateDeploymentRequest() - - request.deployment.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_deployment), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_deployment(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', - 'deployment.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_deployment_field_headers_async(): - client = ConfigAsyncClient( - 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 = config.UpdateDeploymentRequest() - - request.deployment.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_deployment), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.update_deployment(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', - 'deployment.name=name_value', - ) in kw['metadata'] - - -def test_update_deployment_flattened(): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_deployment), - '__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_deployment( - deployment=config.Deployment(terraform_blueprint=config.TerraformBlueprint(gcs_source='gcs_source_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].deployment - mock_val = config.Deployment(terraform_blueprint=config.TerraformBlueprint(gcs_source='gcs_source_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_deployment_flattened_error(): - client = ConfigClient( - 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_deployment( - config.UpdateDeploymentRequest(), - deployment=config.Deployment(terraform_blueprint=config.TerraformBlueprint(gcs_source='gcs_source_value')), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_deployment_flattened_async(): - client = ConfigAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_deployment), - '__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_deployment( - deployment=config.Deployment(terraform_blueprint=config.TerraformBlueprint(gcs_source='gcs_source_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].deployment - mock_val = config.Deployment(terraform_blueprint=config.TerraformBlueprint(gcs_source='gcs_source_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_deployment_flattened_error_async(): - client = ConfigAsyncClient( - 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_deployment( - config.UpdateDeploymentRequest(), - deployment=config.Deployment(terraform_blueprint=config.TerraformBlueprint(gcs_source='gcs_source_value')), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - config.DeleteDeploymentRequest, - dict, -]) -def test_delete_deployment(request_type, transport: str = 'grpc'): - client = ConfigClient( - 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_deployment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.delete_deployment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = config.DeleteDeploymentRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_delete_deployment_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 = ConfigClient( - 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 = config.DeleteDeploymentRequest( - 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_deployment), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_deployment(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == config.DeleteDeploymentRequest( - name='name_value', - request_id='request_id_value', - ) - -def test_delete_deployment_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create 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 = ConfigClient( - 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_deployment in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_deployment] = mock_rpc - request = {} - client.delete_deployment(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_deployment(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_deployment_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 = ConfigAsyncClient( - 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_deployment 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_deployment] = mock_rpc - - request = {} - await client.delete_deployment(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_deployment(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_deployment_async(transport: str = 'grpc_asyncio', request_type=config.DeleteDeploymentRequest): - client = ConfigAsyncClient( - 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_deployment), - '__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_deployment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = config.DeleteDeploymentRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_delete_deployment_async_from_dict(): - await test_delete_deployment_async(request_type=dict) - -def test_delete_deployment_field_headers(): - client = ConfigClient( - 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 = config.DeleteDeploymentRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_deployment), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_deployment(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_deployment_field_headers_async(): - client = ConfigAsyncClient( - 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 = config.DeleteDeploymentRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_deployment), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.delete_deployment(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_deployment_flattened(): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_deployment), - '__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_deployment( - 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_deployment_flattened_error(): - client = ConfigClient( - 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_deployment( - config.DeleteDeploymentRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_deployment_flattened_async(): - client = ConfigAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_deployment), - '__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_deployment( - 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_deployment_flattened_error_async(): - client = ConfigAsyncClient( - 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_deployment( - config.DeleteDeploymentRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - config.ListRevisionsRequest, - dict, -]) -def test_list_revisions(request_type, transport: str = 'grpc'): - client = ConfigClient( - 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_revisions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = config.ListRevisionsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - ) - response = client.list_revisions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = config.ListRevisionsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListRevisionsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -def test_list_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 = ConfigClient( - 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 = config.ListRevisionsRequest( - 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_revisions), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_revisions(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == config.ListRevisionsRequest( - parent='parent_value', - page_token='page_token_value', - filter='filter_value', - order_by='order_by_value', - ) - -def test_list_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 = ConfigClient( - 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_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_revisions] = mock_rpc - request = {} - client.list_revisions(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_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_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 = ConfigAsyncClient( - 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_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_revisions] = mock_rpc - - request = {} - await client.list_revisions(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_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_revisions_async(transport: str = 'grpc_asyncio', request_type=config.ListRevisionsRequest): - client = ConfigAsyncClient( - 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_revisions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(config.ListRevisionsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - )) - response = await client.list_revisions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = config.ListRevisionsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListRevisionsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -@pytest.mark.asyncio -async def test_list_revisions_async_from_dict(): - await test_list_revisions_async(request_type=dict) - -def test_list_revisions_field_headers(): - client = ConfigClient( - 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 = config.ListRevisionsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_revisions), - '__call__') as call: - call.return_value = config.ListRevisionsResponse() - client.list_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_revisions_field_headers_async(): - client = ConfigAsyncClient( - 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 = config.ListRevisionsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_revisions), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.ListRevisionsResponse()) - await client.list_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_revisions_flattened(): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_revisions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = config.ListRevisionsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_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_revisions_flattened_error(): - client = ConfigClient( - 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_revisions( - config.ListRevisionsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_revisions_flattened_async(): - client = ConfigAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_revisions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = config.ListRevisionsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.ListRevisionsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_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_revisions_flattened_error_async(): - client = ConfigAsyncClient( - 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_revisions( - config.ListRevisionsRequest(), - parent='parent_value', - ) - - -def test_list_revisions_pager(transport_name: str = "grpc"): - client = ConfigClient( - 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_revisions), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - config.ListRevisionsResponse( - revisions=[ - config.Revision(), - config.Revision(), - config.Revision(), - ], - next_page_token='abc', - ), - config.ListRevisionsResponse( - revisions=[], - next_page_token='def', - ), - config.ListRevisionsResponse( - revisions=[ - config.Revision(), - ], - next_page_token='ghi', - ), - config.ListRevisionsResponse( - revisions=[ - config.Revision(), - config.Revision(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_revisions(request={}, retry=retry, timeout=timeout) - - assert pager._metadata == expected_metadata - assert pager._retry == retry - assert pager._timeout == timeout - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, config.Revision) - for i in results) -def test_list_revisions_pages(transport_name: str = "grpc"): - client = ConfigClient( - 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_revisions), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - config.ListRevisionsResponse( - revisions=[ - config.Revision(), - config.Revision(), - config.Revision(), - ], - next_page_token='abc', - ), - config.ListRevisionsResponse( - revisions=[], - next_page_token='def', - ), - config.ListRevisionsResponse( - revisions=[ - config.Revision(), - ], - next_page_token='ghi', - ), - config.ListRevisionsResponse( - revisions=[ - config.Revision(), - config.Revision(), - ], - ), - RuntimeError, - ) - pages = list(client.list_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_revisions_async_pager(): - client = ConfigAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_revisions), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - config.ListRevisionsResponse( - revisions=[ - config.Revision(), - config.Revision(), - config.Revision(), - ], - next_page_token='abc', - ), - config.ListRevisionsResponse( - revisions=[], - next_page_token='def', - ), - config.ListRevisionsResponse( - revisions=[ - config.Revision(), - ], - next_page_token='ghi', - ), - config.ListRevisionsResponse( - revisions=[ - config.Revision(), - config.Revision(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_revisions(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, config.Revision) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_revisions_async_pages(): - client = ConfigAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_revisions), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - config.ListRevisionsResponse( - revisions=[ - config.Revision(), - config.Revision(), - config.Revision(), - ], - next_page_token='abc', - ), - config.ListRevisionsResponse( - revisions=[], - next_page_token='def', - ), - config.ListRevisionsResponse( - revisions=[ - config.Revision(), - ], - next_page_token='ghi', - ), - config.ListRevisionsResponse( - revisions=[ - config.Revision(), - config.Revision(), - ], - ), - RuntimeError, - ) - pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.list_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", [ - config.GetRevisionRequest, - dict, -]) -def test_get_revision(request_type, transport: str = 'grpc'): - client = ConfigClient( - 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_revision), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = config.Revision( - name='name_value', - action=config.Revision.Action.CREATE, - state=config.Revision.State.APPLYING, - state_detail='state_detail_value', - error_code=config.Revision.ErrorCode.CLOUD_BUILD_PERMISSION_DENIED, - build='build_value', - logs='logs_value', - error_logs='error_logs_value', - service_account='service_account_value', - import_existing_resources=True, - worker_pool='worker_pool_value', - tf_version_constraint='tf_version_constraint_value', - tf_version='tf_version_value', - quota_validation_results='quota_validation_results_value', - quota_validation=config.QuotaValidation.ENABLED, - ) - response = client.get_revision(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = config.GetRevisionRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, config.Revision) - assert response.name == 'name_value' - assert response.action == config.Revision.Action.CREATE - assert response.state == config.Revision.State.APPLYING - assert response.state_detail == 'state_detail_value' - assert response.error_code == config.Revision.ErrorCode.CLOUD_BUILD_PERMISSION_DENIED - assert response.build == 'build_value' - assert response.logs == 'logs_value' - assert response.error_logs == 'error_logs_value' - assert response.service_account == 'service_account_value' - assert response.import_existing_resources is True - assert response.worker_pool == 'worker_pool_value' - assert response.tf_version_constraint == 'tf_version_constraint_value' - assert response.tf_version == 'tf_version_value' - assert response.quota_validation_results == 'quota_validation_results_value' - assert response.quota_validation == config.QuotaValidation.ENABLED - - -def test_get_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 = ConfigClient( - 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 = config.GetRevisionRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_revision), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_revision(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == config.GetRevisionRequest( - name='name_value', - ) - -def test_get_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 = ConfigClient( - 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_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_revision] = mock_rpc - request = {} - client.get_revision(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_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_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 = ConfigAsyncClient( - 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_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_revision] = mock_rpc - - request = {} - await client.get_revision(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_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_revision_async(transport: str = 'grpc_asyncio', request_type=config.GetRevisionRequest): - client = ConfigAsyncClient( - 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_revision), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(config.Revision( - name='name_value', - action=config.Revision.Action.CREATE, - state=config.Revision.State.APPLYING, - state_detail='state_detail_value', - error_code=config.Revision.ErrorCode.CLOUD_BUILD_PERMISSION_DENIED, - build='build_value', - logs='logs_value', - error_logs='error_logs_value', - service_account='service_account_value', - import_existing_resources=True, - worker_pool='worker_pool_value', - tf_version_constraint='tf_version_constraint_value', - tf_version='tf_version_value', - quota_validation_results='quota_validation_results_value', - quota_validation=config.QuotaValidation.ENABLED, - )) - response = await client.get_revision(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = config.GetRevisionRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, config.Revision) - assert response.name == 'name_value' - assert response.action == config.Revision.Action.CREATE - assert response.state == config.Revision.State.APPLYING - assert response.state_detail == 'state_detail_value' - assert response.error_code == config.Revision.ErrorCode.CLOUD_BUILD_PERMISSION_DENIED - assert response.build == 'build_value' - assert response.logs == 'logs_value' - assert response.error_logs == 'error_logs_value' - assert response.service_account == 'service_account_value' - assert response.import_existing_resources is True - assert response.worker_pool == 'worker_pool_value' - assert response.tf_version_constraint == 'tf_version_constraint_value' - assert response.tf_version == 'tf_version_value' - assert response.quota_validation_results == 'quota_validation_results_value' - assert response.quota_validation == config.QuotaValidation.ENABLED - - -@pytest.mark.asyncio -async def test_get_revision_async_from_dict(): - await test_get_revision_async(request_type=dict) - -def test_get_revision_field_headers(): - client = ConfigClient( - 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 = config.GetRevisionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_revision), - '__call__') as call: - call.return_value = config.Revision() - client.get_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_revision_field_headers_async(): - client = ConfigAsyncClient( - 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 = config.GetRevisionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_revision), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.Revision()) - await client.get_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_revision_flattened(): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_revision), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = config.Revision() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_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_revision_flattened_error(): - client = ConfigClient( - 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_revision( - config.GetRevisionRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_revision_flattened_async(): - client = ConfigAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_revision), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = config.Revision() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.Revision()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_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_revision_flattened_error_async(): - client = ConfigAsyncClient( - 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_revision( - config.GetRevisionRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - config.GetResourceRequest, - dict, -]) -def test_get_resource(request_type, transport: str = 'grpc'): - client = ConfigClient( - 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_resource), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = config.Resource( - name='name_value', - intent=config.Resource.Intent.CREATE, - state=config.Resource.State.PLANNED, - ) - response = client.get_resource(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = config.GetResourceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, config.Resource) - assert response.name == 'name_value' - assert response.intent == config.Resource.Intent.CREATE - assert response.state == config.Resource.State.PLANNED - - -def test_get_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 = ConfigClient( - 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 = config.GetResourceRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_resource), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_resource(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == config.GetResourceRequest( - name='name_value', - ) - -def test_get_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 = ConfigClient( - 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_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_resource] = mock_rpc - request = {} - client.get_resource(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_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_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 = ConfigAsyncClient( - 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_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_resource] = mock_rpc - - request = {} - await client.get_resource(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_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_resource_async(transport: str = 'grpc_asyncio', request_type=config.GetResourceRequest): - client = ConfigAsyncClient( - 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_resource), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(config.Resource( - name='name_value', - intent=config.Resource.Intent.CREATE, - state=config.Resource.State.PLANNED, - )) - response = await client.get_resource(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = config.GetResourceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, config.Resource) - assert response.name == 'name_value' - assert response.intent == config.Resource.Intent.CREATE - assert response.state == config.Resource.State.PLANNED - - -@pytest.mark.asyncio -async def test_get_resource_async_from_dict(): - await test_get_resource_async(request_type=dict) - -def test_get_resource_field_headers(): - client = ConfigClient( - 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 = config.GetResourceRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_resource), - '__call__') as call: - call.return_value = config.Resource() - client.get_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_resource_field_headers_async(): - client = ConfigAsyncClient( - 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 = config.GetResourceRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_resource), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.Resource()) - await client.get_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_resource_flattened(): - client = ConfigClient( - 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), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = config.Resource() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_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_resource_flattened_error(): - client = ConfigClient( - 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_resource( - config.GetResourceRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_resource_flattened_async(): - client = ConfigAsyncClient( - 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), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = config.Resource() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.Resource()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_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_resource_flattened_error_async(): - client = ConfigAsyncClient( - 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_resource( - config.GetResourceRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - config.ListResourcesRequest, - dict, -]) -def test_list_resources(request_type, transport: str = 'grpc'): - client = ConfigClient( - 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_resources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = config.ListResourcesResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - ) - response = client.list_resources(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = config.ListResourcesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListResourcesPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -def test_list_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 = ConfigClient( - 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 = config.ListResourcesRequest( - 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_resources), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_resources(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == config.ListResourcesRequest( - parent='parent_value', - page_token='page_token_value', - filter='filter_value', - order_by='order_by_value', - ) - -def test_list_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 = ConfigClient( - 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_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_resources] = mock_rpc - request = {} - client.list_resources(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_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_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 = ConfigAsyncClient( - 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_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_resources] = mock_rpc - - request = {} - await client.list_resources(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_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_resources_async(transport: str = 'grpc_asyncio', request_type=config.ListResourcesRequest): - client = ConfigAsyncClient( - 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_resources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(config.ListResourcesResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - )) - response = await client.list_resources(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = config.ListResourcesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListResourcesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -@pytest.mark.asyncio -async def test_list_resources_async_from_dict(): - await test_list_resources_async(request_type=dict) - -def test_list_resources_field_headers(): - client = ConfigClient( - 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 = config.ListResourcesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_resources), - '__call__') as call: - call.return_value = config.ListResourcesResponse() - client.list_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_resources_field_headers_async(): - client = ConfigAsyncClient( - 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 = config.ListResourcesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_resources), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.ListResourcesResponse()) - await client.list_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_resources_flattened(): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_resources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = config.ListResourcesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_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_resources_flattened_error(): - client = ConfigClient( - 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_resources( - config.ListResourcesRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_resources_flattened_async(): - client = ConfigAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_resources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = config.ListResourcesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.ListResourcesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_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_resources_flattened_error_async(): - client = ConfigAsyncClient( - 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_resources( - config.ListResourcesRequest(), - parent='parent_value', - ) - - -def test_list_resources_pager(transport_name: str = "grpc"): - client = ConfigClient( - 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_resources), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - config.ListResourcesResponse( - resources=[ - config.Resource(), - config.Resource(), - config.Resource(), - ], - next_page_token='abc', - ), - config.ListResourcesResponse( - resources=[], - next_page_token='def', - ), - config.ListResourcesResponse( - resources=[ - config.Resource(), - ], - next_page_token='ghi', - ), - config.ListResourcesResponse( - resources=[ - config.Resource(), - config.Resource(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_resources(request={}, retry=retry, timeout=timeout) - - assert pager._metadata == expected_metadata - assert pager._retry == retry - assert pager._timeout == timeout - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, config.Resource) - for i in results) -def test_list_resources_pages(transport_name: str = "grpc"): - client = ConfigClient( - 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_resources), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - config.ListResourcesResponse( - resources=[ - config.Resource(), - config.Resource(), - config.Resource(), - ], - next_page_token='abc', - ), - config.ListResourcesResponse( - resources=[], - next_page_token='def', - ), - config.ListResourcesResponse( - resources=[ - config.Resource(), - ], - next_page_token='ghi', - ), - config.ListResourcesResponse( - resources=[ - config.Resource(), - config.Resource(), - ], - ), - RuntimeError, - ) - pages = list(client.list_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_resources_async_pager(): - client = ConfigAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_resources), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - config.ListResourcesResponse( - resources=[ - config.Resource(), - config.Resource(), - config.Resource(), - ], - next_page_token='abc', - ), - config.ListResourcesResponse( - resources=[], - next_page_token='def', - ), - config.ListResourcesResponse( - resources=[ - config.Resource(), - ], - next_page_token='ghi', - ), - config.ListResourcesResponse( - resources=[ - config.Resource(), - config.Resource(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_resources(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, config.Resource) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_resources_async_pages(): - client = ConfigAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_resources), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - config.ListResourcesResponse( - resources=[ - config.Resource(), - config.Resource(), - config.Resource(), - ], - next_page_token='abc', - ), - config.ListResourcesResponse( - resources=[], - next_page_token='def', - ), - config.ListResourcesResponse( - resources=[ - config.Resource(), - ], - next_page_token='ghi', - ), - config.ListResourcesResponse( - resources=[ - config.Resource(), - config.Resource(), - ], - ), - RuntimeError, - ) - pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.list_resources(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", [ - config.ExportDeploymentStatefileRequest, - dict, -]) -def test_export_deployment_statefile(request_type, transport: str = 'grpc'): - client = ConfigClient( - 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.export_deployment_statefile), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = config.Statefile( - signed_uri='signed_uri_value', - ) - response = client.export_deployment_statefile(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = config.ExportDeploymentStatefileRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, config.Statefile) - assert response.signed_uri == 'signed_uri_value' - - -def test_export_deployment_statefile_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 = ConfigClient( - 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 = config.ExportDeploymentStatefileRequest( - parent='parent_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.export_deployment_statefile), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.export_deployment_statefile(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == config.ExportDeploymentStatefileRequest( - parent='parent_value', - ) - -def test_export_deployment_statefile_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create 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 = ConfigClient( - 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.export_deployment_statefile in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.export_deployment_statefile] = mock_rpc - request = {} - client.export_deployment_statefile(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.export_deployment_statefile(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_export_deployment_statefile_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 = ConfigAsyncClient( - 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.export_deployment_statefile 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.export_deployment_statefile] = mock_rpc - - request = {} - await client.export_deployment_statefile(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.export_deployment_statefile(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_export_deployment_statefile_async(transport: str = 'grpc_asyncio', request_type=config.ExportDeploymentStatefileRequest): - client = ConfigAsyncClient( - 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.export_deployment_statefile), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(config.Statefile( - signed_uri='signed_uri_value', - )) - response = await client.export_deployment_statefile(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = config.ExportDeploymentStatefileRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, config.Statefile) - assert response.signed_uri == 'signed_uri_value' - - -@pytest.mark.asyncio -async def test_export_deployment_statefile_async_from_dict(): - await test_export_deployment_statefile_async(request_type=dict) - -def test_export_deployment_statefile_field_headers(): - client = ConfigClient( - 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 = config.ExportDeploymentStatefileRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.export_deployment_statefile), - '__call__') as call: - call.return_value = config.Statefile() - client.export_deployment_statefile(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_export_deployment_statefile_field_headers_async(): - client = ConfigAsyncClient( - 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 = config.ExportDeploymentStatefileRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.export_deployment_statefile), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.Statefile()) - await client.export_deployment_statefile(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'] - - -@pytest.mark.parametrize("request_type", [ - config.ExportRevisionStatefileRequest, - dict, -]) -def test_export_revision_statefile(request_type, transport: str = 'grpc'): - client = ConfigClient( - 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.export_revision_statefile), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = config.Statefile( - signed_uri='signed_uri_value', - ) - response = client.export_revision_statefile(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = config.ExportRevisionStatefileRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, config.Statefile) - assert response.signed_uri == 'signed_uri_value' - - -def test_export_revision_statefile_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 = ConfigClient( - 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 = config.ExportRevisionStatefileRequest( - parent='parent_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.export_revision_statefile), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.export_revision_statefile(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == config.ExportRevisionStatefileRequest( - parent='parent_value', - ) - -def test_export_revision_statefile_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create 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 = ConfigClient( - 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.export_revision_statefile in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.export_revision_statefile] = mock_rpc - request = {} - client.export_revision_statefile(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.export_revision_statefile(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_export_revision_statefile_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 = ConfigAsyncClient( - 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.export_revision_statefile 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.export_revision_statefile] = mock_rpc - - request = {} - await client.export_revision_statefile(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.export_revision_statefile(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_export_revision_statefile_async(transport: str = 'grpc_asyncio', request_type=config.ExportRevisionStatefileRequest): - client = ConfigAsyncClient( - 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.export_revision_statefile), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(config.Statefile( - signed_uri='signed_uri_value', - )) - response = await client.export_revision_statefile(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = config.ExportRevisionStatefileRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, config.Statefile) - assert response.signed_uri == 'signed_uri_value' - - -@pytest.mark.asyncio -async def test_export_revision_statefile_async_from_dict(): - await test_export_revision_statefile_async(request_type=dict) - -def test_export_revision_statefile_field_headers(): - client = ConfigClient( - 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 = config.ExportRevisionStatefileRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.export_revision_statefile), - '__call__') as call: - call.return_value = config.Statefile() - client.export_revision_statefile(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_export_revision_statefile_field_headers_async(): - client = ConfigAsyncClient( - 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 = config.ExportRevisionStatefileRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.export_revision_statefile), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.Statefile()) - await client.export_revision_statefile(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'] - - -@pytest.mark.parametrize("request_type", [ - config.ImportStatefileRequest, - dict, -]) -def test_import_statefile(request_type, transport: str = 'grpc'): - client = ConfigClient( - 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.import_statefile), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = config.Statefile( - signed_uri='signed_uri_value', - ) - response = client.import_statefile(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = config.ImportStatefileRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, config.Statefile) - assert response.signed_uri == 'signed_uri_value' - - -def test_import_statefile_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 = ConfigClient( - 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 = config.ImportStatefileRequest( - parent='parent_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_statefile), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.import_statefile(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == config.ImportStatefileRequest( - parent='parent_value', - ) - -def test_import_statefile_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create 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 = ConfigClient( - 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.import_statefile in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.import_statefile] = mock_rpc - request = {} - client.import_statefile(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.import_statefile(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_import_statefile_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 = ConfigAsyncClient( - 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.import_statefile 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.import_statefile] = mock_rpc - - request = {} - await client.import_statefile(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.import_statefile(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_import_statefile_async(transport: str = 'grpc_asyncio', request_type=config.ImportStatefileRequest): - client = ConfigAsyncClient( - 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.import_statefile), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(config.Statefile( - signed_uri='signed_uri_value', - )) - response = await client.import_statefile(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = config.ImportStatefileRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, config.Statefile) - assert response.signed_uri == 'signed_uri_value' - - -@pytest.mark.asyncio -async def test_import_statefile_async_from_dict(): - await test_import_statefile_async(request_type=dict) - -def test_import_statefile_field_headers(): - client = ConfigClient( - 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 = config.ImportStatefileRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_statefile), - '__call__') as call: - call.return_value = config.Statefile() - client.import_statefile(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_import_statefile_field_headers_async(): - client = ConfigAsyncClient( - 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 = config.ImportStatefileRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_statefile), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.Statefile()) - await client.import_statefile(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_import_statefile_flattened(): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_statefile), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = config.Statefile() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.import_statefile( - parent='parent_value', - lock_id=725, - ) - - # 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].lock_id - mock_val = 725 - assert arg == mock_val - - -def test_import_statefile_flattened_error(): - client = ConfigClient( - 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.import_statefile( - config.ImportStatefileRequest(), - parent='parent_value', - lock_id=725, - ) - -@pytest.mark.asyncio -async def test_import_statefile_flattened_async(): - client = ConfigAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_statefile), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = config.Statefile() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.Statefile()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.import_statefile( - parent='parent_value', - lock_id=725, - ) - - # 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].lock_id - mock_val = 725 - assert arg == mock_val - -@pytest.mark.asyncio -async def test_import_statefile_flattened_error_async(): - client = ConfigAsyncClient( - 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.import_statefile( - config.ImportStatefileRequest(), - parent='parent_value', - lock_id=725, - ) - - -@pytest.mark.parametrize("request_type", [ - config.DeleteStatefileRequest, - dict, -]) -def test_delete_statefile(request_type, transport: str = 'grpc'): - client = ConfigClient( - 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_statefile), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_statefile(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = config.DeleteStatefileRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_statefile_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 = ConfigClient( - 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 = config.DeleteStatefileRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_statefile), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_statefile(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == config.DeleteStatefileRequest( - name='name_value', - ) - -def test_delete_statefile_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create 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 = ConfigClient( - 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_statefile in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_statefile] = mock_rpc - request = {} - client.delete_statefile(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_statefile(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_statefile_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 = ConfigAsyncClient( - 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_statefile 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_statefile] = mock_rpc - - request = {} - await client.delete_statefile(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.delete_statefile(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_statefile_async(transport: str = 'grpc_asyncio', request_type=config.DeleteStatefileRequest): - client = ConfigAsyncClient( - 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_statefile), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_statefile(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = config.DeleteStatefileRequest() - 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_statefile_async_from_dict(): - await test_delete_statefile_async(request_type=dict) - -def test_delete_statefile_field_headers(): - client = ConfigClient( - 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 = config.DeleteStatefileRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_statefile), - '__call__') as call: - call.return_value = None - client.delete_statefile(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_statefile_field_headers_async(): - client = ConfigAsyncClient( - 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 = config.DeleteStatefileRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_statefile), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_statefile(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_statefile_flattened(): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_statefile), - '__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_statefile( - 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_statefile_flattened_error(): - client = ConfigClient( - 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_statefile( - config.DeleteStatefileRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_statefile_flattened_async(): - client = ConfigAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_statefile), - '__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_statefile( - 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_statefile_flattened_error_async(): - client = ConfigAsyncClient( - 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_statefile( - config.DeleteStatefileRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - config.LockDeploymentRequest, - dict, -]) -def test_lock_deployment(request_type, transport: str = 'grpc'): - client = ConfigClient( - 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.lock_deployment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.lock_deployment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = config.LockDeploymentRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_lock_deployment_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 = ConfigClient( - 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 = config.LockDeploymentRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.lock_deployment), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.lock_deployment(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == config.LockDeploymentRequest( - name='name_value', - ) - -def test_lock_deployment_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create 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 = ConfigClient( - 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.lock_deployment in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.lock_deployment] = mock_rpc - request = {} - client.lock_deployment(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.lock_deployment(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_lock_deployment_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 = ConfigAsyncClient( - 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.lock_deployment 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.lock_deployment] = mock_rpc - - request = {} - await client.lock_deployment(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.lock_deployment(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_lock_deployment_async(transport: str = 'grpc_asyncio', request_type=config.LockDeploymentRequest): - client = ConfigAsyncClient( - 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.lock_deployment), - '__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.lock_deployment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = config.LockDeploymentRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_lock_deployment_async_from_dict(): - await test_lock_deployment_async(request_type=dict) - -def test_lock_deployment_field_headers(): - client = ConfigClient( - 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 = config.LockDeploymentRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.lock_deployment), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.lock_deployment(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_lock_deployment_field_headers_async(): - client = ConfigAsyncClient( - 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 = config.LockDeploymentRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.lock_deployment), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.lock_deployment(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_lock_deployment_flattened(): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.lock_deployment), - '__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.lock_deployment( - 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_lock_deployment_flattened_error(): - client = ConfigClient( - 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.lock_deployment( - config.LockDeploymentRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_lock_deployment_flattened_async(): - client = ConfigAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.lock_deployment), - '__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.lock_deployment( - 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_lock_deployment_flattened_error_async(): - client = ConfigAsyncClient( - 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.lock_deployment( - config.LockDeploymentRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - config.UnlockDeploymentRequest, - dict, -]) -def test_unlock_deployment(request_type, transport: str = 'grpc'): - client = ConfigClient( - 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.unlock_deployment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.unlock_deployment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = config.UnlockDeploymentRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_unlock_deployment_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 = ConfigClient( - 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 = config.UnlockDeploymentRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.unlock_deployment), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.unlock_deployment(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == config.UnlockDeploymentRequest( - name='name_value', - ) - -def test_unlock_deployment_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create 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 = ConfigClient( - 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.unlock_deployment in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.unlock_deployment] = mock_rpc - request = {} - client.unlock_deployment(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.unlock_deployment(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_unlock_deployment_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 = ConfigAsyncClient( - 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.unlock_deployment 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.unlock_deployment] = mock_rpc - - request = {} - await client.unlock_deployment(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.unlock_deployment(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_unlock_deployment_async(transport: str = 'grpc_asyncio', request_type=config.UnlockDeploymentRequest): - client = ConfigAsyncClient( - 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.unlock_deployment), - '__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.unlock_deployment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = config.UnlockDeploymentRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_unlock_deployment_async_from_dict(): - await test_unlock_deployment_async(request_type=dict) - -def test_unlock_deployment_field_headers(): - client = ConfigClient( - 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 = config.UnlockDeploymentRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.unlock_deployment), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.unlock_deployment(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_unlock_deployment_field_headers_async(): - client = ConfigAsyncClient( - 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 = config.UnlockDeploymentRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.unlock_deployment), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.unlock_deployment(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_unlock_deployment_flattened(): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.unlock_deployment), - '__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.unlock_deployment( - name='name_value', - lock_id=725, - ) - - # 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].lock_id - mock_val = 725 - assert arg == mock_val - - -def test_unlock_deployment_flattened_error(): - client = ConfigClient( - 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.unlock_deployment( - config.UnlockDeploymentRequest(), - name='name_value', - lock_id=725, - ) - -@pytest.mark.asyncio -async def test_unlock_deployment_flattened_async(): - client = ConfigAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.unlock_deployment), - '__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.unlock_deployment( - name='name_value', - lock_id=725, - ) - - # 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].lock_id - mock_val = 725 - assert arg == mock_val - -@pytest.mark.asyncio -async def test_unlock_deployment_flattened_error_async(): - client = ConfigAsyncClient( - 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.unlock_deployment( - config.UnlockDeploymentRequest(), - name='name_value', - lock_id=725, - ) - - -@pytest.mark.parametrize("request_type", [ - config.ExportLockInfoRequest, - dict, -]) -def test_export_lock_info(request_type, transport: str = 'grpc'): - client = ConfigClient( - 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.export_lock_info), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = config.LockInfo( - lock_id=725, - operation='operation_value', - info='info_value', - who='who_value', - version='version_value', - ) - response = client.export_lock_info(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = config.ExportLockInfoRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, config.LockInfo) - assert response.lock_id == 725 - assert response.operation == 'operation_value' - assert response.info == 'info_value' - assert response.who == 'who_value' - assert response.version == 'version_value' - - -def test_export_lock_info_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 = ConfigClient( - 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 = config.ExportLockInfoRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.export_lock_info), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.export_lock_info(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == config.ExportLockInfoRequest( - name='name_value', - ) - -def test_export_lock_info_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create 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 = ConfigClient( - 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.export_lock_info in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.export_lock_info] = mock_rpc - request = {} - client.export_lock_info(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.export_lock_info(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_export_lock_info_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 = ConfigAsyncClient( - 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.export_lock_info 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.export_lock_info] = mock_rpc - - request = {} - await client.export_lock_info(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.export_lock_info(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_export_lock_info_async(transport: str = 'grpc_asyncio', request_type=config.ExportLockInfoRequest): - client = ConfigAsyncClient( - 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.export_lock_info), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(config.LockInfo( - lock_id=725, - operation='operation_value', - info='info_value', - who='who_value', - version='version_value', - )) - response = await client.export_lock_info(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = config.ExportLockInfoRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, config.LockInfo) - assert response.lock_id == 725 - assert response.operation == 'operation_value' - assert response.info == 'info_value' - assert response.who == 'who_value' - assert response.version == 'version_value' - - -@pytest.mark.asyncio -async def test_export_lock_info_async_from_dict(): - await test_export_lock_info_async(request_type=dict) - -def test_export_lock_info_field_headers(): - client = ConfigClient( - 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 = config.ExportLockInfoRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.export_lock_info), - '__call__') as call: - call.return_value = config.LockInfo() - client.export_lock_info(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_export_lock_info_field_headers_async(): - client = ConfigAsyncClient( - 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 = config.ExportLockInfoRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.export_lock_info), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.LockInfo()) - await client.export_lock_info(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_export_lock_info_flattened(): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.export_lock_info), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = config.LockInfo() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.export_lock_info( - 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_export_lock_info_flattened_error(): - client = ConfigClient( - 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.export_lock_info( - config.ExportLockInfoRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_export_lock_info_flattened_async(): - client = ConfigAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.export_lock_info), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = config.LockInfo() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.LockInfo()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.export_lock_info( - 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_export_lock_info_flattened_error_async(): - client = ConfigAsyncClient( - 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.export_lock_info( - config.ExportLockInfoRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - config.CreatePreviewRequest, - dict, -]) -def test_create_preview(request_type, transport: str = 'grpc'): - client = ConfigClient( - 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_preview), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.create_preview(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = config.CreatePreviewRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_create_preview_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 = ConfigClient( - 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 = config.CreatePreviewRequest( - parent='parent_value', - preview_id='preview_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_preview), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_preview(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == config.CreatePreviewRequest( - parent='parent_value', - preview_id='preview_id_value', - ) - -def test_create_preview_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create 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 = ConfigClient( - 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_preview in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_preview] = mock_rpc - request = {} - client.create_preview(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_preview(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_preview_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 = ConfigAsyncClient( - 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_preview 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_preview] = mock_rpc - - request = {} - await client.create_preview(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_preview(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_preview_async(transport: str = 'grpc_asyncio', request_type=config.CreatePreviewRequest): - client = ConfigAsyncClient( - 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_preview), - '__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_preview(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = config.CreatePreviewRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_create_preview_async_from_dict(): - await test_create_preview_async(request_type=dict) - -def test_create_preview_field_headers(): - client = ConfigClient( - 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 = config.CreatePreviewRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_preview), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_preview(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_preview_field_headers_async(): - client = ConfigAsyncClient( - 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 = config.CreatePreviewRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_preview), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.create_preview(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_preview_flattened(): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_preview), - '__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_preview( - parent='parent_value', - preview=config.Preview(terraform_blueprint=config.TerraformBlueprint(gcs_source='gcs_source_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].preview - mock_val = config.Preview(terraform_blueprint=config.TerraformBlueprint(gcs_source='gcs_source_value')) - assert arg == mock_val - - -def test_create_preview_flattened_error(): - client = ConfigClient( - 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_preview( - config.CreatePreviewRequest(), - parent='parent_value', - preview=config.Preview(terraform_blueprint=config.TerraformBlueprint(gcs_source='gcs_source_value')), - ) - -@pytest.mark.asyncio -async def test_create_preview_flattened_async(): - client = ConfigAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_preview), - '__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_preview( - parent='parent_value', - preview=config.Preview(terraform_blueprint=config.TerraformBlueprint(gcs_source='gcs_source_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].preview - mock_val = config.Preview(terraform_blueprint=config.TerraformBlueprint(gcs_source='gcs_source_value')) - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_preview_flattened_error_async(): - client = ConfigAsyncClient( - 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_preview( - config.CreatePreviewRequest(), - parent='parent_value', - preview=config.Preview(terraform_blueprint=config.TerraformBlueprint(gcs_source='gcs_source_value')), - ) - - -@pytest.mark.parametrize("request_type", [ - config.GetPreviewRequest, - dict, -]) -def test_get_preview(request_type, transport: str = 'grpc'): - client = ConfigClient( - 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_preview), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = config.Preview( - name='name_value', - state=config.Preview.State.CREATING, - deployment='deployment_value', - preview_mode=config.Preview.PreviewMode.DEFAULT, - service_account='service_account_value', - artifacts_gcs_bucket='artifacts_gcs_bucket_value', - worker_pool='worker_pool_value', - error_code=config.Preview.ErrorCode.CLOUD_BUILD_PERMISSION_DENIED, - build='build_value', - error_logs='error_logs_value', - logs='logs_value', - tf_version='tf_version_value', - tf_version_constraint='tf_version_constraint_value', - ) - response = client.get_preview(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = config.GetPreviewRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, config.Preview) - assert response.name == 'name_value' - assert response.state == config.Preview.State.CREATING - assert response.deployment == 'deployment_value' - assert response.preview_mode == config.Preview.PreviewMode.DEFAULT - assert response.service_account == 'service_account_value' - assert response.artifacts_gcs_bucket == 'artifacts_gcs_bucket_value' - assert response.worker_pool == 'worker_pool_value' - assert response.error_code == config.Preview.ErrorCode.CLOUD_BUILD_PERMISSION_DENIED - assert response.build == 'build_value' - assert response.error_logs == 'error_logs_value' - assert response.logs == 'logs_value' - assert response.tf_version == 'tf_version_value' - assert response.tf_version_constraint == 'tf_version_constraint_value' - - -def test_get_preview_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 = ConfigClient( - 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 = config.GetPreviewRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_preview), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_preview(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == config.GetPreviewRequest( - name='name_value', - ) - -def test_get_preview_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create 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 = ConfigClient( - 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_preview in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_preview] = mock_rpc - request = {} - client.get_preview(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_preview(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_preview_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 = ConfigAsyncClient( - 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_preview 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_preview] = mock_rpc - - request = {} - await client.get_preview(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_preview(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_preview_async(transport: str = 'grpc_asyncio', request_type=config.GetPreviewRequest): - client = ConfigAsyncClient( - 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_preview), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(config.Preview( - name='name_value', - state=config.Preview.State.CREATING, - deployment='deployment_value', - preview_mode=config.Preview.PreviewMode.DEFAULT, - service_account='service_account_value', - artifacts_gcs_bucket='artifacts_gcs_bucket_value', - worker_pool='worker_pool_value', - error_code=config.Preview.ErrorCode.CLOUD_BUILD_PERMISSION_DENIED, - build='build_value', - error_logs='error_logs_value', - logs='logs_value', - tf_version='tf_version_value', - tf_version_constraint='tf_version_constraint_value', - )) - response = await client.get_preview(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = config.GetPreviewRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, config.Preview) - assert response.name == 'name_value' - assert response.state == config.Preview.State.CREATING - assert response.deployment == 'deployment_value' - assert response.preview_mode == config.Preview.PreviewMode.DEFAULT - assert response.service_account == 'service_account_value' - assert response.artifacts_gcs_bucket == 'artifacts_gcs_bucket_value' - assert response.worker_pool == 'worker_pool_value' - assert response.error_code == config.Preview.ErrorCode.CLOUD_BUILD_PERMISSION_DENIED - assert response.build == 'build_value' - assert response.error_logs == 'error_logs_value' - assert response.logs == 'logs_value' - assert response.tf_version == 'tf_version_value' - assert response.tf_version_constraint == 'tf_version_constraint_value' - - -@pytest.mark.asyncio -async def test_get_preview_async_from_dict(): - await test_get_preview_async(request_type=dict) - -def test_get_preview_field_headers(): - client = ConfigClient( - 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 = config.GetPreviewRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_preview), - '__call__') as call: - call.return_value = config.Preview() - client.get_preview(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_preview_field_headers_async(): - client = ConfigAsyncClient( - 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 = config.GetPreviewRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_preview), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.Preview()) - await client.get_preview(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_preview_flattened(): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_preview), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = config.Preview() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_preview( - 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_preview_flattened_error(): - client = ConfigClient( - 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_preview( - config.GetPreviewRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_preview_flattened_async(): - client = ConfigAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_preview), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = config.Preview() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.Preview()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_preview( - 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_preview_flattened_error_async(): - client = ConfigAsyncClient( - 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_preview( - config.GetPreviewRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - config.ListPreviewsRequest, - dict, -]) -def test_list_previews(request_type, transport: str = 'grpc'): - client = ConfigClient( - 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_previews), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = config.ListPreviewsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - ) - response = client.list_previews(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = config.ListPreviewsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListPreviewsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -def test_list_previews_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 = ConfigClient( - 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 = config.ListPreviewsRequest( - 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_previews), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_previews(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == config.ListPreviewsRequest( - parent='parent_value', - page_token='page_token_value', - filter='filter_value', - order_by='order_by_value', - ) - -def test_list_previews_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create 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 = ConfigClient( - 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_previews in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_previews] = mock_rpc - request = {} - client.list_previews(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_previews(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_previews_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 = ConfigAsyncClient( - 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_previews 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_previews] = mock_rpc - - request = {} - await client.list_previews(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_previews(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_previews_async(transport: str = 'grpc_asyncio', request_type=config.ListPreviewsRequest): - client = ConfigAsyncClient( - 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_previews), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(config.ListPreviewsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - )) - response = await client.list_previews(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = config.ListPreviewsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListPreviewsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -@pytest.mark.asyncio -async def test_list_previews_async_from_dict(): - await test_list_previews_async(request_type=dict) - -def test_list_previews_field_headers(): - client = ConfigClient( - 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 = config.ListPreviewsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_previews), - '__call__') as call: - call.return_value = config.ListPreviewsResponse() - client.list_previews(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_previews_field_headers_async(): - client = ConfigAsyncClient( - 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 = config.ListPreviewsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_previews), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.ListPreviewsResponse()) - await client.list_previews(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_previews_flattened(): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_previews), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = config.ListPreviewsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_previews( - 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_previews_flattened_error(): - client = ConfigClient( - 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_previews( - config.ListPreviewsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_previews_flattened_async(): - client = ConfigAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_previews), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = config.ListPreviewsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.ListPreviewsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_previews( - 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_previews_flattened_error_async(): - client = ConfigAsyncClient( - 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_previews( - config.ListPreviewsRequest(), - parent='parent_value', - ) - - -def test_list_previews_pager(transport_name: str = "grpc"): - client = ConfigClient( - 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_previews), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - config.ListPreviewsResponse( - previews=[ - config.Preview(), - config.Preview(), - config.Preview(), - ], - next_page_token='abc', - ), - config.ListPreviewsResponse( - previews=[], - next_page_token='def', - ), - config.ListPreviewsResponse( - previews=[ - config.Preview(), - ], - next_page_token='ghi', - ), - config.ListPreviewsResponse( - previews=[ - config.Preview(), - config.Preview(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_previews(request={}, retry=retry, timeout=timeout) - - assert pager._metadata == expected_metadata - assert pager._retry == retry - assert pager._timeout == timeout - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, config.Preview) - for i in results) -def test_list_previews_pages(transport_name: str = "grpc"): - client = ConfigClient( - 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_previews), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - config.ListPreviewsResponse( - previews=[ - config.Preview(), - config.Preview(), - config.Preview(), - ], - next_page_token='abc', - ), - config.ListPreviewsResponse( - previews=[], - next_page_token='def', - ), - config.ListPreviewsResponse( - previews=[ - config.Preview(), - ], - next_page_token='ghi', - ), - config.ListPreviewsResponse( - previews=[ - config.Preview(), - config.Preview(), - ], - ), - RuntimeError, - ) - pages = list(client.list_previews(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_previews_async_pager(): - client = ConfigAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_previews), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - config.ListPreviewsResponse( - previews=[ - config.Preview(), - config.Preview(), - config.Preview(), - ], - next_page_token='abc', - ), - config.ListPreviewsResponse( - previews=[], - next_page_token='def', - ), - config.ListPreviewsResponse( - previews=[ - config.Preview(), - ], - next_page_token='ghi', - ), - config.ListPreviewsResponse( - previews=[ - config.Preview(), - config.Preview(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_previews(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, config.Preview) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_previews_async_pages(): - client = ConfigAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_previews), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - config.ListPreviewsResponse( - previews=[ - config.Preview(), - config.Preview(), - config.Preview(), - ], - next_page_token='abc', - ), - config.ListPreviewsResponse( - previews=[], - next_page_token='def', - ), - config.ListPreviewsResponse( - previews=[ - config.Preview(), - ], - next_page_token='ghi', - ), - config.ListPreviewsResponse( - previews=[ - config.Preview(), - config.Preview(), - ], - ), - RuntimeError, - ) - pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.list_previews(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", [ - config.DeletePreviewRequest, - dict, -]) -def test_delete_preview(request_type, transport: str = 'grpc'): - client = ConfigClient( - 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_preview), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.delete_preview(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = config.DeletePreviewRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_delete_preview_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 = ConfigClient( - 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 = config.DeletePreviewRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_preview), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_preview(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == config.DeletePreviewRequest( - name='name_value', - ) - -def test_delete_preview_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create 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 = ConfigClient( - 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_preview in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_preview] = mock_rpc - request = {} - client.delete_preview(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_preview(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_preview_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 = ConfigAsyncClient( - 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_preview 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_preview] = mock_rpc - - request = {} - await client.delete_preview(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_preview(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_preview_async(transport: str = 'grpc_asyncio', request_type=config.DeletePreviewRequest): - client = ConfigAsyncClient( - 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_preview), - '__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_preview(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = config.DeletePreviewRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_delete_preview_async_from_dict(): - await test_delete_preview_async(request_type=dict) - -def test_delete_preview_field_headers(): - client = ConfigClient( - 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 = config.DeletePreviewRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_preview), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_preview(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_preview_field_headers_async(): - client = ConfigAsyncClient( - 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 = config.DeletePreviewRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_preview), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.delete_preview(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_preview_flattened(): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_preview), - '__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_preview( - 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_preview_flattened_error(): - client = ConfigClient( - 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_preview( - config.DeletePreviewRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_preview_flattened_async(): - client = ConfigAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_preview), - '__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_preview( - 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_preview_flattened_error_async(): - client = ConfigAsyncClient( - 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_preview( - config.DeletePreviewRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - config.ExportPreviewResultRequest, - dict, -]) -def test_export_preview_result(request_type, transport: str = 'grpc'): - client = ConfigClient( - 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.export_preview_result), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = config.ExportPreviewResultResponse( - ) - response = client.export_preview_result(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = config.ExportPreviewResultRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, config.ExportPreviewResultResponse) - - -def test_export_preview_result_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 = ConfigClient( - 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 = config.ExportPreviewResultRequest( - parent='parent_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.export_preview_result), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.export_preview_result(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == config.ExportPreviewResultRequest( - parent='parent_value', - ) - -def test_export_preview_result_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create 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 = ConfigClient( - 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.export_preview_result in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.export_preview_result] = mock_rpc - request = {} - client.export_preview_result(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.export_preview_result(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_export_preview_result_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 = ConfigAsyncClient( - 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.export_preview_result 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.export_preview_result] = mock_rpc - - request = {} - await client.export_preview_result(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.export_preview_result(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_export_preview_result_async(transport: str = 'grpc_asyncio', request_type=config.ExportPreviewResultRequest): - client = ConfigAsyncClient( - 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.export_preview_result), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(config.ExportPreviewResultResponse( - )) - response = await client.export_preview_result(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = config.ExportPreviewResultRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, config.ExportPreviewResultResponse) - - -@pytest.mark.asyncio -async def test_export_preview_result_async_from_dict(): - await test_export_preview_result_async(request_type=dict) - -def test_export_preview_result_field_headers(): - client = ConfigClient( - 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 = config.ExportPreviewResultRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.export_preview_result), - '__call__') as call: - call.return_value = config.ExportPreviewResultResponse() - client.export_preview_result(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_export_preview_result_field_headers_async(): - client = ConfigAsyncClient( - 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 = config.ExportPreviewResultRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.export_preview_result), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.ExportPreviewResultResponse()) - await client.export_preview_result(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'] - - -@pytest.mark.parametrize("request_type", [ - config.ListTerraformVersionsRequest, - dict, -]) -def test_list_terraform_versions(request_type, transport: str = 'grpc'): - client = ConfigClient( - 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_terraform_versions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = config.ListTerraformVersionsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - ) - response = client.list_terraform_versions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = config.ListTerraformVersionsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListTerraformVersionsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -def test_list_terraform_versions_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 = ConfigClient( - 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 = config.ListTerraformVersionsRequest( - 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_terraform_versions), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_terraform_versions(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == config.ListTerraformVersionsRequest( - parent='parent_value', - page_token='page_token_value', - filter='filter_value', - order_by='order_by_value', - ) - -def test_list_terraform_versions_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create 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 = ConfigClient( - 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_terraform_versions in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_terraform_versions] = mock_rpc - request = {} - client.list_terraform_versions(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_terraform_versions(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_terraform_versions_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 = ConfigAsyncClient( - 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_terraform_versions 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_terraform_versions] = mock_rpc - - request = {} - await client.list_terraform_versions(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_terraform_versions(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_terraform_versions_async(transport: str = 'grpc_asyncio', request_type=config.ListTerraformVersionsRequest): - client = ConfigAsyncClient( - 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_terraform_versions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(config.ListTerraformVersionsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - )) - response = await client.list_terraform_versions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = config.ListTerraformVersionsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListTerraformVersionsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -@pytest.mark.asyncio -async def test_list_terraform_versions_async_from_dict(): - await test_list_terraform_versions_async(request_type=dict) - -def test_list_terraform_versions_field_headers(): - client = ConfigClient( - 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 = config.ListTerraformVersionsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_terraform_versions), - '__call__') as call: - call.return_value = config.ListTerraformVersionsResponse() - client.list_terraform_versions(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_terraform_versions_field_headers_async(): - client = ConfigAsyncClient( - 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 = config.ListTerraformVersionsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_terraform_versions), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.ListTerraformVersionsResponse()) - await client.list_terraform_versions(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_terraform_versions_flattened(): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_terraform_versions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = config.ListTerraformVersionsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_terraform_versions( - 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_terraform_versions_flattened_error(): - client = ConfigClient( - 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_terraform_versions( - config.ListTerraformVersionsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_terraform_versions_flattened_async(): - client = ConfigAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_terraform_versions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = config.ListTerraformVersionsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.ListTerraformVersionsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_terraform_versions( - 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_terraform_versions_flattened_error_async(): - client = ConfigAsyncClient( - 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_terraform_versions( - config.ListTerraformVersionsRequest(), - parent='parent_value', - ) - - -def test_list_terraform_versions_pager(transport_name: str = "grpc"): - client = ConfigClient( - 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_terraform_versions), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - config.ListTerraformVersionsResponse( - terraform_versions=[ - config.TerraformVersion(), - config.TerraformVersion(), - config.TerraformVersion(), - ], - next_page_token='abc', - ), - config.ListTerraformVersionsResponse( - terraform_versions=[], - next_page_token='def', - ), - config.ListTerraformVersionsResponse( - terraform_versions=[ - config.TerraformVersion(), - ], - next_page_token='ghi', - ), - config.ListTerraformVersionsResponse( - terraform_versions=[ - config.TerraformVersion(), - config.TerraformVersion(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_terraform_versions(request={}, retry=retry, timeout=timeout) - - assert pager._metadata == expected_metadata - assert pager._retry == retry - assert pager._timeout == timeout - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, config.TerraformVersion) - for i in results) -def test_list_terraform_versions_pages(transport_name: str = "grpc"): - client = ConfigClient( - 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_terraform_versions), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - config.ListTerraformVersionsResponse( - terraform_versions=[ - config.TerraformVersion(), - config.TerraformVersion(), - config.TerraformVersion(), - ], - next_page_token='abc', - ), - config.ListTerraformVersionsResponse( - terraform_versions=[], - next_page_token='def', - ), - config.ListTerraformVersionsResponse( - terraform_versions=[ - config.TerraformVersion(), - ], - next_page_token='ghi', - ), - config.ListTerraformVersionsResponse( - terraform_versions=[ - config.TerraformVersion(), - config.TerraformVersion(), - ], - ), - RuntimeError, - ) - pages = list(client.list_terraform_versions(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_terraform_versions_async_pager(): - client = ConfigAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_terraform_versions), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - config.ListTerraformVersionsResponse( - terraform_versions=[ - config.TerraformVersion(), - config.TerraformVersion(), - config.TerraformVersion(), - ], - next_page_token='abc', - ), - config.ListTerraformVersionsResponse( - terraform_versions=[], - next_page_token='def', - ), - config.ListTerraformVersionsResponse( - terraform_versions=[ - config.TerraformVersion(), - ], - next_page_token='ghi', - ), - config.ListTerraformVersionsResponse( - terraform_versions=[ - config.TerraformVersion(), - config.TerraformVersion(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_terraform_versions(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, config.TerraformVersion) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_terraform_versions_async_pages(): - client = ConfigAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_terraform_versions), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - config.ListTerraformVersionsResponse( - terraform_versions=[ - config.TerraformVersion(), - config.TerraformVersion(), - config.TerraformVersion(), - ], - next_page_token='abc', - ), - config.ListTerraformVersionsResponse( - terraform_versions=[], - next_page_token='def', - ), - config.ListTerraformVersionsResponse( - terraform_versions=[ - config.TerraformVersion(), - ], - next_page_token='ghi', - ), - config.ListTerraformVersionsResponse( - terraform_versions=[ - config.TerraformVersion(), - config.TerraformVersion(), - ], - ), - RuntimeError, - ) - pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.list_terraform_versions(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", [ - config.GetTerraformVersionRequest, - dict, -]) -def test_get_terraform_version(request_type, transport: str = 'grpc'): - client = ConfigClient( - 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_terraform_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = config.TerraformVersion( - name='name_value', - state=config.TerraformVersion.State.ACTIVE, - ) - response = client.get_terraform_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = config.GetTerraformVersionRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, config.TerraformVersion) - assert response.name == 'name_value' - assert response.state == config.TerraformVersion.State.ACTIVE - - -def test_get_terraform_version_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 = ConfigClient( - 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 = config.GetTerraformVersionRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_terraform_version), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_terraform_version(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == config.GetTerraformVersionRequest( - name='name_value', - ) - -def test_get_terraform_version_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create 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 = ConfigClient( - 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_terraform_version in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_terraform_version] = mock_rpc - request = {} - client.get_terraform_version(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_terraform_version(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_terraform_version_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 = ConfigAsyncClient( - 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_terraform_version 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_terraform_version] = mock_rpc - - request = {} - await client.get_terraform_version(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_terraform_version(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_terraform_version_async(transport: str = 'grpc_asyncio', request_type=config.GetTerraformVersionRequest): - client = ConfigAsyncClient( - 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_terraform_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(config.TerraformVersion( - name='name_value', - state=config.TerraformVersion.State.ACTIVE, - )) - response = await client.get_terraform_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = config.GetTerraformVersionRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, config.TerraformVersion) - assert response.name == 'name_value' - assert response.state == config.TerraformVersion.State.ACTIVE - - -@pytest.mark.asyncio -async def test_get_terraform_version_async_from_dict(): - await test_get_terraform_version_async(request_type=dict) - -def test_get_terraform_version_field_headers(): - client = ConfigClient( - 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 = config.GetTerraformVersionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_terraform_version), - '__call__') as call: - call.return_value = config.TerraformVersion() - client.get_terraform_version(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_terraform_version_field_headers_async(): - client = ConfigAsyncClient( - 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 = config.GetTerraformVersionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_terraform_version), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.TerraformVersion()) - await client.get_terraform_version(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_terraform_version_flattened(): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_terraform_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = config.TerraformVersion() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_terraform_version( - 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_terraform_version_flattened_error(): - client = ConfigClient( - 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_terraform_version( - config.GetTerraformVersionRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_terraform_version_flattened_async(): - client = ConfigAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_terraform_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = config.TerraformVersion() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.TerraformVersion()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_terraform_version( - 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_terraform_version_flattened_error_async(): - client = ConfigAsyncClient( - 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_terraform_version( - config.GetTerraformVersionRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - config.ListResourceChangesRequest, - dict, -]) -def test_list_resource_changes(request_type, transport: str = 'grpc'): - client = ConfigClient( - 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_changes), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = config.ListResourceChangesResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - ) - response = client.list_resource_changes(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = config.ListResourceChangesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListResourceChangesPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -def test_list_resource_changes_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 = ConfigClient( - 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 = config.ListResourceChangesRequest( - 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_changes), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_resource_changes(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == config.ListResourceChangesRequest( - parent='parent_value', - page_token='page_token_value', - filter='filter_value', - order_by='order_by_value', - ) - -def test_list_resource_changes_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create 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 = ConfigClient( - 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_changes in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_changes] = mock_rpc - request = {} - client.list_resource_changes(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_resource_changes(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_changes_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 = ConfigAsyncClient( - 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_changes 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_changes] = mock_rpc - - request = {} - await client.list_resource_changes(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_resource_changes(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_changes_async(transport: str = 'grpc_asyncio', request_type=config.ListResourceChangesRequest): - client = ConfigAsyncClient( - 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_changes), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(config.ListResourceChangesResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - )) - response = await client.list_resource_changes(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = config.ListResourceChangesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListResourceChangesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -@pytest.mark.asyncio -async def test_list_resource_changes_async_from_dict(): - await test_list_resource_changes_async(request_type=dict) - -def test_list_resource_changes_field_headers(): - client = ConfigClient( - 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 = config.ListResourceChangesRequest() - - 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_changes), - '__call__') as call: - call.return_value = config.ListResourceChangesResponse() - client.list_resource_changes(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_changes_field_headers_async(): - client = ConfigAsyncClient( - 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 = config.ListResourceChangesRequest() - - 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_changes), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.ListResourceChangesResponse()) - await client.list_resource_changes(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_changes_flattened(): - client = ConfigClient( - 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_changes), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = config.ListResourceChangesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_resource_changes( - 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_changes_flattened_error(): - client = ConfigClient( - 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_changes( - config.ListResourceChangesRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_resource_changes_flattened_async(): - client = ConfigAsyncClient( - 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_changes), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = config.ListResourceChangesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.ListResourceChangesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_resource_changes( - 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_changes_flattened_error_async(): - client = ConfigAsyncClient( - 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_changes( - config.ListResourceChangesRequest(), - parent='parent_value', - ) - - -def test_list_resource_changes_pager(transport_name: str = "grpc"): - client = ConfigClient( - 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_changes), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - config.ListResourceChangesResponse( - resource_changes=[ - config.ResourceChange(), - config.ResourceChange(), - config.ResourceChange(), - ], - next_page_token='abc', - ), - config.ListResourceChangesResponse( - resource_changes=[], - next_page_token='def', - ), - config.ListResourceChangesResponse( - resource_changes=[ - config.ResourceChange(), - ], - next_page_token='ghi', - ), - config.ListResourceChangesResponse( - resource_changes=[ - config.ResourceChange(), - config.ResourceChange(), - ], - ), - 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_changes(request={}, retry=retry, timeout=timeout) - - assert pager._metadata == expected_metadata - assert pager._retry == retry - assert pager._timeout == timeout - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, config.ResourceChange) - for i in results) -def test_list_resource_changes_pages(transport_name: str = "grpc"): - client = ConfigClient( - 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_changes), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - config.ListResourceChangesResponse( - resource_changes=[ - config.ResourceChange(), - config.ResourceChange(), - config.ResourceChange(), - ], - next_page_token='abc', - ), - config.ListResourceChangesResponse( - resource_changes=[], - next_page_token='def', - ), - config.ListResourceChangesResponse( - resource_changes=[ - config.ResourceChange(), - ], - next_page_token='ghi', - ), - config.ListResourceChangesResponse( - resource_changes=[ - config.ResourceChange(), - config.ResourceChange(), - ], - ), - RuntimeError, - ) - pages = list(client.list_resource_changes(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_changes_async_pager(): - client = ConfigAsyncClient( - 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_changes), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - config.ListResourceChangesResponse( - resource_changes=[ - config.ResourceChange(), - config.ResourceChange(), - config.ResourceChange(), - ], - next_page_token='abc', - ), - config.ListResourceChangesResponse( - resource_changes=[], - next_page_token='def', - ), - config.ListResourceChangesResponse( - resource_changes=[ - config.ResourceChange(), - ], - next_page_token='ghi', - ), - config.ListResourceChangesResponse( - resource_changes=[ - config.ResourceChange(), - config.ResourceChange(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_resource_changes(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, config.ResourceChange) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_resource_changes_async_pages(): - client = ConfigAsyncClient( - 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_changes), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - config.ListResourceChangesResponse( - resource_changes=[ - config.ResourceChange(), - config.ResourceChange(), - config.ResourceChange(), - ], - next_page_token='abc', - ), - config.ListResourceChangesResponse( - resource_changes=[], - next_page_token='def', - ), - config.ListResourceChangesResponse( - resource_changes=[ - config.ResourceChange(), - ], - next_page_token='ghi', - ), - config.ListResourceChangesResponse( - resource_changes=[ - config.ResourceChange(), - config.ResourceChange(), - ], - ), - RuntimeError, - ) - pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.list_resource_changes(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", [ - config.GetResourceChangeRequest, - dict, -]) -def test_get_resource_change(request_type, transport: str = 'grpc'): - client = ConfigClient( - 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_resource_change), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = config.ResourceChange( - name='name_value', - intent=config.ResourceChange.Intent.CREATE, - ) - response = client.get_resource_change(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = config.GetResourceChangeRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, config.ResourceChange) - assert response.name == 'name_value' - assert response.intent == config.ResourceChange.Intent.CREATE - - -def test_get_resource_change_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 = ConfigClient( - 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 = config.GetResourceChangeRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_resource_change), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_resource_change(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == config.GetResourceChangeRequest( - name='name_value', - ) - -def test_get_resource_change_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create 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 = ConfigClient( - 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_resource_change in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_change] = mock_rpc - request = {} - client.get_resource_change(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_resource_change(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_resource_change_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 = ConfigAsyncClient( - 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_resource_change 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_resource_change] = mock_rpc - - request = {} - await client.get_resource_change(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_resource_change(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_resource_change_async(transport: str = 'grpc_asyncio', request_type=config.GetResourceChangeRequest): - client = ConfigAsyncClient( - 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_resource_change), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(config.ResourceChange( - name='name_value', - intent=config.ResourceChange.Intent.CREATE, - )) - response = await client.get_resource_change(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = config.GetResourceChangeRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, config.ResourceChange) - assert response.name == 'name_value' - assert response.intent == config.ResourceChange.Intent.CREATE - - -@pytest.mark.asyncio -async def test_get_resource_change_async_from_dict(): - await test_get_resource_change_async(request_type=dict) - -def test_get_resource_change_field_headers(): - client = ConfigClient( - 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 = config.GetResourceChangeRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_resource_change), - '__call__') as call: - call.return_value = config.ResourceChange() - client.get_resource_change(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_resource_change_field_headers_async(): - client = ConfigAsyncClient( - 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 = config.GetResourceChangeRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_resource_change), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.ResourceChange()) - await client.get_resource_change(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_resource_change_flattened(): - client = ConfigClient( - 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_change), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = config.ResourceChange() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_resource_change( - 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_resource_change_flattened_error(): - client = ConfigClient( - 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_resource_change( - config.GetResourceChangeRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_resource_change_flattened_async(): - client = ConfigAsyncClient( - 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_change), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = config.ResourceChange() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.ResourceChange()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_resource_change( - 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_resource_change_flattened_error_async(): - client = ConfigAsyncClient( - 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_resource_change( - config.GetResourceChangeRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - config.ListResourceDriftsRequest, - dict, -]) -def test_list_resource_drifts(request_type, transport: str = 'grpc'): - client = ConfigClient( - 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_drifts), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = config.ListResourceDriftsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - ) - response = client.list_resource_drifts(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = config.ListResourceDriftsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListResourceDriftsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -def test_list_resource_drifts_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 = ConfigClient( - 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 = config.ListResourceDriftsRequest( - 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_drifts), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_resource_drifts(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == config.ListResourceDriftsRequest( - parent='parent_value', - page_token='page_token_value', - filter='filter_value', - order_by='order_by_value', - ) - -def test_list_resource_drifts_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create 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 = ConfigClient( - 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_drifts in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_drifts] = mock_rpc - request = {} - client.list_resource_drifts(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_resource_drifts(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_drifts_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 = ConfigAsyncClient( - 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_drifts 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_drifts] = mock_rpc - - request = {} - await client.list_resource_drifts(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_resource_drifts(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_drifts_async(transport: str = 'grpc_asyncio', request_type=config.ListResourceDriftsRequest): - client = ConfigAsyncClient( - 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_drifts), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(config.ListResourceDriftsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - )) - response = await client.list_resource_drifts(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = config.ListResourceDriftsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListResourceDriftsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -@pytest.mark.asyncio -async def test_list_resource_drifts_async_from_dict(): - await test_list_resource_drifts_async(request_type=dict) - -def test_list_resource_drifts_field_headers(): - client = ConfigClient( - 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 = config.ListResourceDriftsRequest() - - 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_drifts), - '__call__') as call: - call.return_value = config.ListResourceDriftsResponse() - client.list_resource_drifts(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_drifts_field_headers_async(): - client = ConfigAsyncClient( - 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 = config.ListResourceDriftsRequest() - - 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_drifts), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.ListResourceDriftsResponse()) - await client.list_resource_drifts(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_drifts_flattened(): - client = ConfigClient( - 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_drifts), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = config.ListResourceDriftsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_resource_drifts( - 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_drifts_flattened_error(): - client = ConfigClient( - 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_drifts( - config.ListResourceDriftsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_resource_drifts_flattened_async(): - client = ConfigAsyncClient( - 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_drifts), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = config.ListResourceDriftsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.ListResourceDriftsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_resource_drifts( - 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_drifts_flattened_error_async(): - client = ConfigAsyncClient( - 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_drifts( - config.ListResourceDriftsRequest(), - parent='parent_value', - ) - - -def test_list_resource_drifts_pager(transport_name: str = "grpc"): - client = ConfigClient( - 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_drifts), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - config.ListResourceDriftsResponse( - resource_drifts=[ - config.ResourceDrift(), - config.ResourceDrift(), - config.ResourceDrift(), - ], - next_page_token='abc', - ), - config.ListResourceDriftsResponse( - resource_drifts=[], - next_page_token='def', - ), - config.ListResourceDriftsResponse( - resource_drifts=[ - config.ResourceDrift(), - ], - next_page_token='ghi', - ), - config.ListResourceDriftsResponse( - resource_drifts=[ - config.ResourceDrift(), - config.ResourceDrift(), - ], - ), - 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_drifts(request={}, retry=retry, timeout=timeout) - - assert pager._metadata == expected_metadata - assert pager._retry == retry - assert pager._timeout == timeout - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, config.ResourceDrift) - for i in results) -def test_list_resource_drifts_pages(transport_name: str = "grpc"): - client = ConfigClient( - 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_drifts), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - config.ListResourceDriftsResponse( - resource_drifts=[ - config.ResourceDrift(), - config.ResourceDrift(), - config.ResourceDrift(), - ], - next_page_token='abc', - ), - config.ListResourceDriftsResponse( - resource_drifts=[], - next_page_token='def', - ), - config.ListResourceDriftsResponse( - resource_drifts=[ - config.ResourceDrift(), - ], - next_page_token='ghi', - ), - config.ListResourceDriftsResponse( - resource_drifts=[ - config.ResourceDrift(), - config.ResourceDrift(), - ], - ), - RuntimeError, - ) - pages = list(client.list_resource_drifts(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_drifts_async_pager(): - client = ConfigAsyncClient( - 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_drifts), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - config.ListResourceDriftsResponse( - resource_drifts=[ - config.ResourceDrift(), - config.ResourceDrift(), - config.ResourceDrift(), - ], - next_page_token='abc', - ), - config.ListResourceDriftsResponse( - resource_drifts=[], - next_page_token='def', - ), - config.ListResourceDriftsResponse( - resource_drifts=[ - config.ResourceDrift(), - ], - next_page_token='ghi', - ), - config.ListResourceDriftsResponse( - resource_drifts=[ - config.ResourceDrift(), - config.ResourceDrift(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_resource_drifts(request={},) - assert async_pager.next_page_token == 'abc' - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, config.ResourceDrift) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_resource_drifts_async_pages(): - client = ConfigAsyncClient( - 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_drifts), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - config.ListResourceDriftsResponse( - resource_drifts=[ - config.ResourceDrift(), - config.ResourceDrift(), - config.ResourceDrift(), - ], - next_page_token='abc', - ), - config.ListResourceDriftsResponse( - resource_drifts=[], - next_page_token='def', - ), - config.ListResourceDriftsResponse( - resource_drifts=[ - config.ResourceDrift(), - ], - next_page_token='ghi', - ), - config.ListResourceDriftsResponse( - resource_drifts=[ - config.ResourceDrift(), - config.ResourceDrift(), - ], - ), - RuntimeError, - ) - pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.list_resource_drifts(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", [ - config.GetResourceDriftRequest, - dict, -]) -def test_get_resource_drift(request_type, transport: str = 'grpc'): - client = ConfigClient( - 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_resource_drift), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = config.ResourceDrift( - name='name_value', - ) - response = client.get_resource_drift(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = config.GetResourceDriftRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, config.ResourceDrift) - assert response.name == 'name_value' - - -def test_get_resource_drift_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 = ConfigClient( - 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 = config.GetResourceDriftRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_resource_drift), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_resource_drift(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == config.GetResourceDriftRequest( - name='name_value', - ) - -def test_get_resource_drift_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create 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 = ConfigClient( - 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_resource_drift in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_drift] = mock_rpc - request = {} - client.get_resource_drift(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_resource_drift(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_resource_drift_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 = ConfigAsyncClient( - 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_resource_drift 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_resource_drift] = mock_rpc - - request = {} - await client.get_resource_drift(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_resource_drift(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_resource_drift_async(transport: str = 'grpc_asyncio', request_type=config.GetResourceDriftRequest): - client = ConfigAsyncClient( - 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_resource_drift), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(config.ResourceDrift( - name='name_value', - )) - response = await client.get_resource_drift(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = config.GetResourceDriftRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, config.ResourceDrift) - assert response.name == 'name_value' - - -@pytest.mark.asyncio -async def test_get_resource_drift_async_from_dict(): - await test_get_resource_drift_async(request_type=dict) - -def test_get_resource_drift_field_headers(): - client = ConfigClient( - 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 = config.GetResourceDriftRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_resource_drift), - '__call__') as call: - call.return_value = config.ResourceDrift() - client.get_resource_drift(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_resource_drift_field_headers_async(): - client = ConfigAsyncClient( - 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 = config.GetResourceDriftRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_resource_drift), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.ResourceDrift()) - await client.get_resource_drift(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_resource_drift_flattened(): - client = ConfigClient( - 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_drift), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = config.ResourceDrift() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_resource_drift( - 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_resource_drift_flattened_error(): - client = ConfigClient( - 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_resource_drift( - config.GetResourceDriftRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_resource_drift_flattened_async(): - client = ConfigAsyncClient( - 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_drift), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = config.ResourceDrift() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.ResourceDrift()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_resource_drift( - 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_resource_drift_flattened_error_async(): - client = ConfigAsyncClient( - 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_resource_drift( - config.GetResourceDriftRequest(), - name='name_value', - ) - - -def test_list_deployments_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 = ConfigClient( - 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_deployments in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_deployments] = mock_rpc - - request = {} - client.list_deployments(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_deployments(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_deployments_rest_required_fields(request_type=config.ListDeploymentsRequest): - transport_class = transports.ConfigRestTransport - - 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 - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_deployments._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_deployments._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("filter", "order_by", "page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = config.ListDeploymentsResponse() - # 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 = config.ListDeploymentsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_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_deployments(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_deployments_rest_unset_required_fields(): - transport = transports.ConfigRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_deployments._get_unset_required_fields({}) - assert set(unset_fields) == (set(("filter", "orderBy", "pageSize", "pageToken", )) & set(("parent", ))) - - -def test_list_deployments_rest_flattened(): - client = ConfigClient( - 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 = config.ListDeploymentsResponse() - - # 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 = config.ListDeploymentsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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_deployments(**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/*}/deployments" % client.transport._host, args[1]) - - -def test_list_deployments_rest_flattened_error(transport: str = 'rest'): - client = ConfigClient( - 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_deployments( - config.ListDeploymentsRequest(), - parent='parent_value', - ) - - -def test_list_deployments_rest_pager(transport: str = 'rest'): - client = ConfigClient( - 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 = ( - config.ListDeploymentsResponse( - deployments=[ - config.Deployment(), - config.Deployment(), - config.Deployment(), - ], - next_page_token='abc', - ), - config.ListDeploymentsResponse( - deployments=[], - next_page_token='def', - ), - config.ListDeploymentsResponse( - deployments=[ - config.Deployment(), - ], - next_page_token='ghi', - ), - config.ListDeploymentsResponse( - deployments=[ - config.Deployment(), - config.Deployment(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(config.ListDeploymentsResponse.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_deployments(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, config.Deployment) - for i in results) - - pages = list(client.list_deployments(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_get_deployment_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 = ConfigClient( - 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_deployment in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_deployment] = mock_rpc - - request = {} - client.get_deployment(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_deployment(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_deployment_rest_required_fields(request_type=config.GetDeploymentRequest): - transport_class = transports.ConfigRestTransport - - 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 - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_deployment._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_deployment._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = config.Deployment() - # 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 = config.Deployment.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_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_deployment(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_deployment_rest_unset_required_fields(): - transport = transports.ConfigRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_deployment._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_get_deployment_rest_flattened(): - client = ConfigClient( - 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 = config.Deployment() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/deployments/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 = config.Deployment.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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_deployment(**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/*/deployments/*}" % client.transport._host, args[1]) - - -def test_get_deployment_rest_flattened_error(transport: str = 'rest'): - client = ConfigClient( - 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_deployment( - config.GetDeploymentRequest(), - name='name_value', - ) - - -def test_create_deployment_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 = ConfigClient( - 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_deployment in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_deployment] = mock_rpc - - request = {} - client.create_deployment(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_deployment(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_deployment_rest_required_fields(request_type=config.CreateDeploymentRequest): - transport_class = transports.ConfigRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["deployment_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 "deploymentId" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_deployment._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "deploymentId" in jsonified_request - assert jsonified_request["deploymentId"] == request_init["deployment_id"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["deploymentId"] = 'deployment_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_deployment._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("deployment_id", "request_id", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - assert "deploymentId" in jsonified_request - assert jsonified_request["deploymentId"] == 'deployment_id_value' - - client = ConfigClient( - 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_deployment(request) - - expected_params = [ - ( - "deploymentId", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_deployment_rest_unset_required_fields(): - transport = transports.ConfigRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_deployment._get_unset_required_fields({}) - assert set(unset_fields) == (set(("deploymentId", "requestId", )) & set(("parent", "deploymentId", "deployment", ))) - - -def test_create_deployment_rest_flattened(): - client = ConfigClient( - 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', - deployment=config.Deployment(terraform_blueprint=config.TerraformBlueprint(gcs_source='gcs_source_value')), - deployment_id='deployment_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_deployment(**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/*}/deployments" % client.transport._host, args[1]) - - -def test_create_deployment_rest_flattened_error(transport: str = 'rest'): - client = ConfigClient( - 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_deployment( - config.CreateDeploymentRequest(), - parent='parent_value', - deployment=config.Deployment(terraform_blueprint=config.TerraformBlueprint(gcs_source='gcs_source_value')), - deployment_id='deployment_id_value', - ) - - -def test_update_deployment_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 = ConfigClient( - 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_deployment in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_deployment] = mock_rpc - - request = {} - client.update_deployment(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_deployment(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_deployment_rest_required_fields(request_type=config.UpdateDeploymentRequest): - transport_class = transports.ConfigRestTransport - - 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 - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_deployment._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_deployment._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("request_id", "update_mask", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = ConfigClient( - 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_deployment(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_deployment_rest_unset_required_fields(): - transport = transports.ConfigRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_deployment._get_unset_required_fields({}) - assert set(unset_fields) == (set(("requestId", "updateMask", )) & set(("deployment", ))) - - -def test_update_deployment_rest_flattened(): - client = ConfigClient( - 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 = {'deployment': {'name': 'projects/sample1/locations/sample2/deployments/sample3'}} - - # get truthy value for each flattened field - mock_args = dict( - deployment=config.Deployment(terraform_blueprint=config.TerraformBlueprint(gcs_source='gcs_source_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_deployment(**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/{deployment.name=projects/*/locations/*/deployments/*}" % client.transport._host, args[1]) - - -def test_update_deployment_rest_flattened_error(transport: str = 'rest'): - client = ConfigClient( - 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_deployment( - config.UpdateDeploymentRequest(), - deployment=config.Deployment(terraform_blueprint=config.TerraformBlueprint(gcs_source='gcs_source_value')), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_delete_deployment_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 = ConfigClient( - 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_deployment in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_deployment] = mock_rpc - - request = {} - client.delete_deployment(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_deployment(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_deployment_rest_required_fields(request_type=config.DeleteDeploymentRequest): - transport_class = transports.ConfigRestTransport - - 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 - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_deployment._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_deployment._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("delete_policy", "force", "request_id", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = ConfigClient( - 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_deployment(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_deployment_rest_unset_required_fields(): - transport = transports.ConfigRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_deployment._get_unset_required_fields({}) - assert set(unset_fields) == (set(("deletePolicy", "force", "requestId", )) & set(("name", ))) - - -def test_delete_deployment_rest_flattened(): - client = ConfigClient( - 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/deployments/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_deployment(**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/*/deployments/*}" % client.transport._host, args[1]) - - -def test_delete_deployment_rest_flattened_error(transport: str = 'rest'): - client = ConfigClient( - 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_deployment( - config.DeleteDeploymentRequest(), - name='name_value', - ) - - -def test_list_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 = ConfigClient( - 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_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_revisions] = mock_rpc - - request = {} - client.list_revisions(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_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_revisions_rest_required_fields(request_type=config.ListRevisionsRequest): - transport_class = transports.ConfigRestTransport - - 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 - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_revisions._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_revisions._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("filter", "order_by", "page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = config.ListRevisionsResponse() - # 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 = config.ListRevisionsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_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_revisions(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_revisions_rest_unset_required_fields(): - transport = transports.ConfigRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_revisions._get_unset_required_fields({}) - assert set(unset_fields) == (set(("filter", "orderBy", "pageSize", "pageToken", )) & set(("parent", ))) - - -def test_list_revisions_rest_flattened(): - client = ConfigClient( - 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 = config.ListRevisionsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2/deployments/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 = config.ListRevisionsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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_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/v1/{parent=projects/*/locations/*/deployments/*}/revisions" % client.transport._host, args[1]) - - -def test_list_revisions_rest_flattened_error(transport: str = 'rest'): - client = ConfigClient( - 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_revisions( - config.ListRevisionsRequest(), - parent='parent_value', - ) - - -def test_list_revisions_rest_pager(transport: str = 'rest'): - client = ConfigClient( - 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 = ( - config.ListRevisionsResponse( - revisions=[ - config.Revision(), - config.Revision(), - config.Revision(), - ], - next_page_token='abc', - ), - config.ListRevisionsResponse( - revisions=[], - next_page_token='def', - ), - config.ListRevisionsResponse( - revisions=[ - config.Revision(), - ], - next_page_token='ghi', - ), - config.ListRevisionsResponse( - revisions=[ - config.Revision(), - config.Revision(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(config.ListRevisionsResponse.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/deployments/sample3'} - - pager = client.list_revisions(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, config.Revision) - for i in results) - - pages = list(client.list_revisions(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_get_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 = ConfigClient( - 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_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_revision] = mock_rpc - - request = {} - client.get_revision(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_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_revision_rest_required_fields(request_type=config.GetRevisionRequest): - transport_class = transports.ConfigRestTransport - - 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 - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_revision._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_revision._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = config.Revision() - # 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 = config.Revision.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_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_revision(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_revision_rest_unset_required_fields(): - transport = transports.ConfigRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_revision._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_get_revision_rest_flattened(): - client = ConfigClient( - 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 = config.Revision() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/deployments/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 = config.Revision.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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_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/v1/{name=projects/*/locations/*/deployments/*/revisions/*}" % client.transport._host, args[1]) - - -def test_get_revision_rest_flattened_error(transport: str = 'rest'): - client = ConfigClient( - 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_revision( - config.GetRevisionRequest(), - name='name_value', - ) - - -def test_get_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 = ConfigClient( - 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 in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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] = mock_rpc - - request = {} - client.get_resource(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_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_resource_rest_required_fields(request_type=config.GetResourceRequest): - transport_class = transports.ConfigRestTransport - - 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 - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_resource._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_resource._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = config.Resource() - # 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 = config.Resource.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_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(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_resource_rest_unset_required_fields(): - transport = transports.ConfigRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_resource._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_get_resource_rest_flattened(): - client = ConfigClient( - 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 = config.Resource() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/deployments/sample3/revisions/sample4/resources/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 = config.Resource.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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(**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/*/deployments/*/revisions/*/resources/*}" % client.transport._host, args[1]) - - -def test_get_resource_rest_flattened_error(transport: str = 'rest'): - client = ConfigClient( - 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( - config.GetResourceRequest(), - name='name_value', - ) - - -def test_list_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 = ConfigClient( - 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_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_resources] = mock_rpc - - request = {} - client.list_resources(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_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_resources_rest_required_fields(request_type=config.ListResourcesRequest): - transport_class = transports.ConfigRestTransport - - 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 - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_resources._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_resources._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("filter", "order_by", "page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = config.ListResourcesResponse() - # 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 = config.ListResourcesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_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_resources(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_resources_rest_unset_required_fields(): - transport = transports.ConfigRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_resources._get_unset_required_fields({}) - assert set(unset_fields) == (set(("filter", "orderBy", "pageSize", "pageToken", )) & set(("parent", ))) - - -def test_list_resources_rest_flattened(): - client = ConfigClient( - 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 = config.ListResourcesResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2/deployments/sample3/revisions/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 = config.ListResourcesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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_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/v1/{parent=projects/*/locations/*/deployments/*/revisions/*}/resources" % client.transport._host, args[1]) - - -def test_list_resources_rest_flattened_error(transport: str = 'rest'): - client = ConfigClient( - 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_resources( - config.ListResourcesRequest(), - parent='parent_value', - ) - - -def test_list_resources_rest_pager(transport: str = 'rest'): - client = ConfigClient( - 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 = ( - config.ListResourcesResponse( - resources=[ - config.Resource(), - config.Resource(), - config.Resource(), - ], - next_page_token='abc', - ), - config.ListResourcesResponse( - resources=[], - next_page_token='def', - ), - config.ListResourcesResponse( - resources=[ - config.Resource(), - ], - next_page_token='ghi', - ), - config.ListResourcesResponse( - resources=[ - config.Resource(), - config.Resource(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(config.ListResourcesResponse.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/deployments/sample3/revisions/sample4'} - - pager = client.list_resources(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, config.Resource) - for i in results) - - pages = list(client.list_resources(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_export_deployment_statefile_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 = ConfigClient( - 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.export_deployment_statefile in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.export_deployment_statefile] = mock_rpc - - request = {} - client.export_deployment_statefile(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.export_deployment_statefile(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_export_deployment_statefile_rest_required_fields(request_type=config.ExportDeploymentStatefileRequest): - transport_class = transports.ConfigRestTransport - - 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 - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).export_deployment_statefile._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).export_deployment_statefile._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = config.Statefile() - # 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 = config.Statefile.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.export_deployment_statefile(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_export_deployment_statefile_rest_unset_required_fields(): - transport = transports.ConfigRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.export_deployment_statefile._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", ))) - - -def test_export_revision_statefile_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 = ConfigClient( - 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.export_revision_statefile in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.export_revision_statefile] = mock_rpc - - request = {} - client.export_revision_statefile(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.export_revision_statefile(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_export_revision_statefile_rest_required_fields(request_type=config.ExportRevisionStatefileRequest): - transport_class = transports.ConfigRestTransport - - 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 - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).export_revision_statefile._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).export_revision_statefile._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = config.Statefile() - # 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 = config.Statefile.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.export_revision_statefile(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_export_revision_statefile_rest_unset_required_fields(): - transport = transports.ConfigRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.export_revision_statefile._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", ))) - - -def test_import_statefile_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 = ConfigClient( - 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.import_statefile in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.import_statefile] = mock_rpc - - request = {} - client.import_statefile(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.import_statefile(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_import_statefile_rest_required_fields(request_type=config.ImportStatefileRequest): - transport_class = transports.ConfigRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["lock_id"] = 0 - 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 - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).import_statefile._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - jsonified_request["lockId"] = 725 - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).import_statefile._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - assert "lockId" in jsonified_request - assert jsonified_request["lockId"] == 725 - - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = config.Statefile() - # 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 = config.Statefile.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.import_statefile(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_import_statefile_rest_unset_required_fields(): - transport = transports.ConfigRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.import_statefile._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "lockId", ))) - - -def test_import_statefile_rest_flattened(): - client = ConfigClient( - 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 = config.Statefile() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2/deployments/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - lock_id=725, - ) - 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 = config.Statefile.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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.import_statefile(**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/*/deployments/*}:importState" % client.transport._host, args[1]) - - -def test_import_statefile_rest_flattened_error(transport: str = 'rest'): - client = ConfigClient( - 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.import_statefile( - config.ImportStatefileRequest(), - parent='parent_value', - lock_id=725, - ) - - -def test_delete_statefile_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 = ConfigClient( - 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_statefile in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_statefile] = mock_rpc - - request = {} - client.delete_statefile(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.delete_statefile(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_statefile_rest_required_fields(request_type=config.DeleteStatefileRequest): - transport_class = transports.ConfigRestTransport - - request_init = {} - request_init["name"] = "" - request_init["lock_id"] = 0 - 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 - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_statefile._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - jsonified_request["lockId"] = 725 - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_statefile._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - assert "lockId" in jsonified_request - assert jsonified_request["lockId"] == 725 - - client = ConfigClient( - 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.delete_statefile(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_statefile_rest_unset_required_fields(): - transport = transports.ConfigRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_statefile._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", "lockId", ))) - - -def test_delete_statefile_rest_flattened(): - client = ConfigClient( - 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': 'projects/sample1/locations/sample2/deployments/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 = '' - response_value._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_statefile(**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/*/deployments/*}:deleteState" % client.transport._host, args[1]) - - -def test_delete_statefile_rest_flattened_error(transport: str = 'rest'): - client = ConfigClient( - 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_statefile( - config.DeleteStatefileRequest(), - name='name_value', - ) - - -def test_lock_deployment_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 = ConfigClient( - 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.lock_deployment in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.lock_deployment] = mock_rpc - - request = {} - client.lock_deployment(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.lock_deployment(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_lock_deployment_rest_required_fields(request_type=config.LockDeploymentRequest): - transport_class = transports.ConfigRestTransport - - 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 - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).lock_deployment._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).lock_deployment._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = ConfigClient( - 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.lock_deployment(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_lock_deployment_rest_unset_required_fields(): - transport = transports.ConfigRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.lock_deployment._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_lock_deployment_rest_flattened(): - client = ConfigClient( - 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/deployments/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.lock_deployment(**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/*/deployments/*}:lock" % client.transport._host, args[1]) - - -def test_lock_deployment_rest_flattened_error(transport: str = 'rest'): - client = ConfigClient( - 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.lock_deployment( - config.LockDeploymentRequest(), - name='name_value', - ) - - -def test_unlock_deployment_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 = ConfigClient( - 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.unlock_deployment in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.unlock_deployment] = mock_rpc - - request = {} - client.unlock_deployment(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.unlock_deployment(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_unlock_deployment_rest_required_fields(request_type=config.UnlockDeploymentRequest): - transport_class = transports.ConfigRestTransport - - request_init = {} - request_init["name"] = "" - request_init["lock_id"] = 0 - 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 - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).unlock_deployment._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - jsonified_request["lockId"] = 725 - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).unlock_deployment._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - assert "lockId" in jsonified_request - assert jsonified_request["lockId"] == 725 - - client = ConfigClient( - 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.unlock_deployment(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_unlock_deployment_rest_unset_required_fields(): - transport = transports.ConfigRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.unlock_deployment._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", "lockId", ))) - - -def test_unlock_deployment_rest_flattened(): - client = ConfigClient( - 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/deployments/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - lock_id=725, - ) - 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.unlock_deployment(**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/*/deployments/*}:unlock" % client.transport._host, args[1]) - - -def test_unlock_deployment_rest_flattened_error(transport: str = 'rest'): - client = ConfigClient( - 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.unlock_deployment( - config.UnlockDeploymentRequest(), - name='name_value', - lock_id=725, - ) - - -def test_export_lock_info_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 = ConfigClient( - 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.export_lock_info in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.export_lock_info] = mock_rpc - - request = {} - client.export_lock_info(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.export_lock_info(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_export_lock_info_rest_required_fields(request_type=config.ExportLockInfoRequest): - transport_class = transports.ConfigRestTransport - - 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 - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).export_lock_info._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).export_lock_info._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = config.LockInfo() - # 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 = config.LockInfo.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.export_lock_info(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_export_lock_info_rest_unset_required_fields(): - transport = transports.ConfigRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.export_lock_info._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_export_lock_info_rest_flattened(): - client = ConfigClient( - 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 = config.LockInfo() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/deployments/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 = config.LockInfo.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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.export_lock_info(**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/*/deployments/*}:exportLock" % client.transport._host, args[1]) - - -def test_export_lock_info_rest_flattened_error(transport: str = 'rest'): - client = ConfigClient( - 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.export_lock_info( - config.ExportLockInfoRequest(), - name='name_value', - ) - - -def test_create_preview_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 = ConfigClient( - 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_preview in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_preview] = mock_rpc - - request = {} - client.create_preview(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_preview(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_preview_rest_required_fields(request_type=config.CreatePreviewRequest): - transport_class = transports.ConfigRestTransport - - 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 - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_preview._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_preview._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("preview_id", "request_id", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = ConfigClient( - 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_preview(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_preview_rest_unset_required_fields(): - transport = transports.ConfigRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_preview._get_unset_required_fields({}) - assert set(unset_fields) == (set(("previewId", "requestId", )) & set(("parent", "preview", ))) - - -def test_create_preview_rest_flattened(): - client = ConfigClient( - 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', - preview=config.Preview(terraform_blueprint=config.TerraformBlueprint(gcs_source='gcs_source_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_preview(**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/*}/previews" % client.transport._host, args[1]) - - -def test_create_preview_rest_flattened_error(transport: str = 'rest'): - client = ConfigClient( - 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_preview( - config.CreatePreviewRequest(), - parent='parent_value', - preview=config.Preview(terraform_blueprint=config.TerraformBlueprint(gcs_source='gcs_source_value')), - ) - - -def test_get_preview_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 = ConfigClient( - 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_preview in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_preview] = mock_rpc - - request = {} - client.get_preview(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_preview(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_preview_rest_required_fields(request_type=config.GetPreviewRequest): - transport_class = transports.ConfigRestTransport - - 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 - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_preview._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_preview._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = config.Preview() - # 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 = config.Preview.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_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_preview(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_preview_rest_unset_required_fields(): - transport = transports.ConfigRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_preview._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_get_preview_rest_flattened(): - client = ConfigClient( - 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 = config.Preview() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/previews/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 = config.Preview.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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_preview(**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/*/previews/*}" % client.transport._host, args[1]) - - -def test_get_preview_rest_flattened_error(transport: str = 'rest'): - client = ConfigClient( - 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_preview( - config.GetPreviewRequest(), - name='name_value', - ) - - -def test_list_previews_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 = ConfigClient( - 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_previews in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_previews] = mock_rpc - - request = {} - client.list_previews(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_previews(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_previews_rest_required_fields(request_type=config.ListPreviewsRequest): - transport_class = transports.ConfigRestTransport - - 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 - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_previews._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_previews._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("filter", "order_by", "page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = config.ListPreviewsResponse() - # 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 = config.ListPreviewsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_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_previews(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_previews_rest_unset_required_fields(): - transport = transports.ConfigRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_previews._get_unset_required_fields({}) - assert set(unset_fields) == (set(("filter", "orderBy", "pageSize", "pageToken", )) & set(("parent", ))) - - -def test_list_previews_rest_flattened(): - client = ConfigClient( - 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 = config.ListPreviewsResponse() - - # 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 = config.ListPreviewsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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_previews(**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/*}/previews" % client.transport._host, args[1]) - - -def test_list_previews_rest_flattened_error(transport: str = 'rest'): - client = ConfigClient( - 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_previews( - config.ListPreviewsRequest(), - parent='parent_value', - ) - - -def test_list_previews_rest_pager(transport: str = 'rest'): - client = ConfigClient( - 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 = ( - config.ListPreviewsResponse( - previews=[ - config.Preview(), - config.Preview(), - config.Preview(), - ], - next_page_token='abc', - ), - config.ListPreviewsResponse( - previews=[], - next_page_token='def', - ), - config.ListPreviewsResponse( - previews=[ - config.Preview(), - ], - next_page_token='ghi', - ), - config.ListPreviewsResponse( - previews=[ - config.Preview(), - config.Preview(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(config.ListPreviewsResponse.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_previews(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, config.Preview) - for i in results) - - pages = list(client.list_previews(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_delete_preview_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 = ConfigClient( - 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_preview in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_preview] = mock_rpc - - request = {} - client.delete_preview(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_preview(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_preview_rest_required_fields(request_type=config.DeletePreviewRequest): - transport_class = transports.ConfigRestTransport - - 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 - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_preview._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_preview._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("request_id", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = ConfigClient( - 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_preview(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_preview_rest_unset_required_fields(): - transport = transports.ConfigRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_preview._get_unset_required_fields({}) - assert set(unset_fields) == (set(("requestId", )) & set(("name", ))) - - -def test_delete_preview_rest_flattened(): - client = ConfigClient( - 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/previews/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_preview(**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/*/previews/*}" % client.transport._host, args[1]) - - -def test_delete_preview_rest_flattened_error(transport: str = 'rest'): - client = ConfigClient( - 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_preview( - config.DeletePreviewRequest(), - name='name_value', - ) - - -def test_export_preview_result_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 = ConfigClient( - 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.export_preview_result in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.export_preview_result] = mock_rpc - - request = {} - client.export_preview_result(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.export_preview_result(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_export_preview_result_rest_required_fields(request_type=config.ExportPreviewResultRequest): - transport_class = transports.ConfigRestTransport - - 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 - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).export_preview_result._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).export_preview_result._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = config.ExportPreviewResultResponse() - # 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 = config.ExportPreviewResultResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.export_preview_result(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_export_preview_result_rest_unset_required_fields(): - transport = transports.ConfigRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.export_preview_result._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", ))) - - -def test_list_terraform_versions_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 = ConfigClient( - 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_terraform_versions in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_terraform_versions] = mock_rpc - - request = {} - client.list_terraform_versions(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_terraform_versions(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_terraform_versions_rest_required_fields(request_type=config.ListTerraformVersionsRequest): - transport_class = transports.ConfigRestTransport - - 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 - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_terraform_versions._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_terraform_versions._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("filter", "order_by", "page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = config.ListTerraformVersionsResponse() - # 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 = config.ListTerraformVersionsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_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_terraform_versions(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_terraform_versions_rest_unset_required_fields(): - transport = transports.ConfigRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_terraform_versions._get_unset_required_fields({}) - assert set(unset_fields) == (set(("filter", "orderBy", "pageSize", "pageToken", )) & set(("parent", ))) - - -def test_list_terraform_versions_rest_flattened(): - client = ConfigClient( - 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 = config.ListTerraformVersionsResponse() - - # 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 = config.ListTerraformVersionsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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_terraform_versions(**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/*}/terraformVersions" % client.transport._host, args[1]) - - -def test_list_terraform_versions_rest_flattened_error(transport: str = 'rest'): - client = ConfigClient( - 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_terraform_versions( - config.ListTerraformVersionsRequest(), - parent='parent_value', - ) - - -def test_list_terraform_versions_rest_pager(transport: str = 'rest'): - client = ConfigClient( - 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 = ( - config.ListTerraformVersionsResponse( - terraform_versions=[ - config.TerraformVersion(), - config.TerraformVersion(), - config.TerraformVersion(), - ], - next_page_token='abc', - ), - config.ListTerraformVersionsResponse( - terraform_versions=[], - next_page_token='def', - ), - config.ListTerraformVersionsResponse( - terraform_versions=[ - config.TerraformVersion(), - ], - next_page_token='ghi', - ), - config.ListTerraformVersionsResponse( - terraform_versions=[ - config.TerraformVersion(), - config.TerraformVersion(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(config.ListTerraformVersionsResponse.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_terraform_versions(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, config.TerraformVersion) - for i in results) - - pages = list(client.list_terraform_versions(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_get_terraform_version_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 = ConfigClient( - 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_terraform_version in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_terraform_version] = mock_rpc - - request = {} - client.get_terraform_version(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_terraform_version(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_terraform_version_rest_required_fields(request_type=config.GetTerraformVersionRequest): - transport_class = transports.ConfigRestTransport - - 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 - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_terraform_version._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_terraform_version._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = config.TerraformVersion() - # 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 = config.TerraformVersion.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_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_terraform_version(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_terraform_version_rest_unset_required_fields(): - transport = transports.ConfigRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_terraform_version._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_get_terraform_version_rest_flattened(): - client = ConfigClient( - 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 = config.TerraformVersion() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/terraformVersions/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 = config.TerraformVersion.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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_terraform_version(**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/*/terraformVersions/*}" % client.transport._host, args[1]) - - -def test_get_terraform_version_rest_flattened_error(transport: str = 'rest'): - client = ConfigClient( - 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_terraform_version( - config.GetTerraformVersionRequest(), - name='name_value', - ) - - -def test_list_resource_changes_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 = ConfigClient( - 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_changes in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_changes] = mock_rpc - - request = {} - client.list_resource_changes(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_resource_changes(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_changes_rest_required_fields(request_type=config.ListResourceChangesRequest): - transport_class = transports.ConfigRestTransport - - 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 - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_resource_changes._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_resource_changes._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("filter", "order_by", "page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = config.ListResourceChangesResponse() - # 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 = config.ListResourceChangesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_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_changes(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_resource_changes_rest_unset_required_fields(): - transport = transports.ConfigRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_resource_changes._get_unset_required_fields({}) - assert set(unset_fields) == (set(("filter", "orderBy", "pageSize", "pageToken", )) & set(("parent", ))) - - -def test_list_resource_changes_rest_flattened(): - client = ConfigClient( - 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 = config.ListResourceChangesResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2/previews/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 = config.ListResourceChangesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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_changes(**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/*/previews/*}/resourceChanges" % client.transport._host, args[1]) - - -def test_list_resource_changes_rest_flattened_error(transport: str = 'rest'): - client = ConfigClient( - 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_changes( - config.ListResourceChangesRequest(), - parent='parent_value', - ) - - -def test_list_resource_changes_rest_pager(transport: str = 'rest'): - client = ConfigClient( - 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 = ( - config.ListResourceChangesResponse( - resource_changes=[ - config.ResourceChange(), - config.ResourceChange(), - config.ResourceChange(), - ], - next_page_token='abc', - ), - config.ListResourceChangesResponse( - resource_changes=[], - next_page_token='def', - ), - config.ListResourceChangesResponse( - resource_changes=[ - config.ResourceChange(), - ], - next_page_token='ghi', - ), - config.ListResourceChangesResponse( - resource_changes=[ - config.ResourceChange(), - config.ResourceChange(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(config.ListResourceChangesResponse.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/previews/sample3'} - - pager = client.list_resource_changes(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, config.ResourceChange) - for i in results) - - pages = list(client.list_resource_changes(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_get_resource_change_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 = ConfigClient( - 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_change in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_change] = mock_rpc - - request = {} - client.get_resource_change(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_resource_change(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_change_rest_required_fields(request_type=config.GetResourceChangeRequest): - transport_class = transports.ConfigRestTransport - - 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 - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_resource_change._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_resource_change._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = config.ResourceChange() - # 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 = config.ResourceChange.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_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_change(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_resource_change_rest_unset_required_fields(): - transport = transports.ConfigRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_resource_change._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_get_resource_change_rest_flattened(): - client = ConfigClient( - 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 = config.ResourceChange() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/previews/sample3/resourceChanges/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 = config.ResourceChange.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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_change(**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/*/previews/*/resourceChanges/*}" % client.transport._host, args[1]) - - -def test_get_resource_change_rest_flattened_error(transport: str = 'rest'): - client = ConfigClient( - 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_change( - config.GetResourceChangeRequest(), - name='name_value', - ) - - -def test_list_resource_drifts_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 = ConfigClient( - 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_drifts in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_drifts] = mock_rpc - - request = {} - client.list_resource_drifts(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_resource_drifts(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_drifts_rest_required_fields(request_type=config.ListResourceDriftsRequest): - transport_class = transports.ConfigRestTransport - - 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 - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_resource_drifts._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_resource_drifts._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("filter", "order_by", "page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = config.ListResourceDriftsResponse() - # 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 = config.ListResourceDriftsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_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_drifts(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_resource_drifts_rest_unset_required_fields(): - transport = transports.ConfigRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_resource_drifts._get_unset_required_fields({}) - assert set(unset_fields) == (set(("filter", "orderBy", "pageSize", "pageToken", )) & set(("parent", ))) - - -def test_list_resource_drifts_rest_flattened(): - client = ConfigClient( - 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 = config.ListResourceDriftsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2/previews/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 = config.ListResourceDriftsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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_drifts(**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/*/previews/*}/resourceDrifts" % client.transport._host, args[1]) - - -def test_list_resource_drifts_rest_flattened_error(transport: str = 'rest'): - client = ConfigClient( - 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_drifts( - config.ListResourceDriftsRequest(), - parent='parent_value', - ) - - -def test_list_resource_drifts_rest_pager(transport: str = 'rest'): - client = ConfigClient( - 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 = ( - config.ListResourceDriftsResponse( - resource_drifts=[ - config.ResourceDrift(), - config.ResourceDrift(), - config.ResourceDrift(), - ], - next_page_token='abc', - ), - config.ListResourceDriftsResponse( - resource_drifts=[], - next_page_token='def', - ), - config.ListResourceDriftsResponse( - resource_drifts=[ - config.ResourceDrift(), - ], - next_page_token='ghi', - ), - config.ListResourceDriftsResponse( - resource_drifts=[ - config.ResourceDrift(), - config.ResourceDrift(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(config.ListResourceDriftsResponse.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/previews/sample3'} - - pager = client.list_resource_drifts(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, config.ResourceDrift) - for i in results) - - pages = list(client.list_resource_drifts(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_get_resource_drift_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 = ConfigClient( - 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_drift in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_drift] = mock_rpc - - request = {} - client.get_resource_drift(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_resource_drift(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_drift_rest_required_fields(request_type=config.GetResourceDriftRequest): - transport_class = transports.ConfigRestTransport - - 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 - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_resource_drift._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_resource_drift._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = config.ResourceDrift() - # 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 = config.ResourceDrift.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_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_drift(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_resource_drift_rest_unset_required_fields(): - transport = transports.ConfigRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_resource_drift._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_get_resource_drift_rest_flattened(): - client = ConfigClient( - 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 = config.ResourceDrift() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/previews/sample3/resourceDrifts/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 = config.ResourceDrift.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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_drift(**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/*/previews/*/resourceDrifts/*}" % client.transport._host, args[1]) - - -def test_get_resource_drift_rest_flattened_error(transport: str = 'rest'): - client = ConfigClient( - 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_drift( - config.GetResourceDriftRequest(), - name='name_value', - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.ConfigGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.ConfigGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ConfigClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.ConfigGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ConfigClient( - 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 = ConfigClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.ConfigGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ConfigClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.ConfigGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = ConfigClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.ConfigGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.ConfigGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.ConfigGrpcTransport, - transports.ConfigGrpcAsyncIOTransport, - transports.ConfigRestTransport, -]) -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 = ConfigClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" - - -def test_initialize_client_w_grpc(): - client = ConfigClient( - 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_deployments_empty_call_grpc(): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_deployments), - '__call__') as call: - call.return_value = config.ListDeploymentsResponse() - client.list_deployments(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = config.ListDeploymentsRequest() - - assert args[0] == request_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_deployment_empty_call_grpc(): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_deployment), - '__call__') as call: - call.return_value = config.Deployment() - client.get_deployment(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = config.GetDeploymentRequest() - - assert args[0] == request_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_deployment_empty_call_grpc(): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_deployment), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_deployment(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = config.CreateDeploymentRequest() - - assert args[0] == request_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_deployment_empty_call_grpc(): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_deployment), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_deployment(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = config.UpdateDeploymentRequest() - - assert args[0] == request_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_deployment_empty_call_grpc(): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_deployment), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_deployment(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = config.DeleteDeploymentRequest() - - assert args[0] == request_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_revisions_empty_call_grpc(): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_revisions), - '__call__') as call: - call.return_value = config.ListRevisionsResponse() - client.list_revisions(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = config.ListRevisionsRequest() - - assert args[0] == request_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_revision_empty_call_grpc(): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_revision), - '__call__') as call: - call.return_value = config.Revision() - client.get_revision(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = config.GetRevisionRequest() - - assert args[0] == request_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_empty_call_grpc(): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_resource), - '__call__') as call: - call.return_value = config.Resource() - client.get_resource(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = config.GetResourceRequest() - - assert args[0] == request_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_resources_empty_call_grpc(): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_resources), - '__call__') as call: - call.return_value = config.ListResourcesResponse() - client.list_resources(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = config.ListResourcesRequest() - - assert args[0] == request_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_export_deployment_statefile_empty_call_grpc(): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.export_deployment_statefile), - '__call__') as call: - call.return_value = config.Statefile() - client.export_deployment_statefile(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = config.ExportDeploymentStatefileRequest() - - assert args[0] == request_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_export_revision_statefile_empty_call_grpc(): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.export_revision_statefile), - '__call__') as call: - call.return_value = config.Statefile() - client.export_revision_statefile(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = config.ExportRevisionStatefileRequest() - - assert args[0] == request_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_import_statefile_empty_call_grpc(): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.import_statefile), - '__call__') as call: - call.return_value = config.Statefile() - client.import_statefile(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = config.ImportStatefileRequest() - - assert args[0] == request_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_statefile_empty_call_grpc(): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_statefile), - '__call__') as call: - call.return_value = None - client.delete_statefile(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = config.DeleteStatefileRequest() - - assert args[0] == request_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_lock_deployment_empty_call_grpc(): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.lock_deployment), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.lock_deployment(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = config.LockDeploymentRequest() - - assert args[0] == request_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_unlock_deployment_empty_call_grpc(): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.unlock_deployment), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.unlock_deployment(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = config.UnlockDeploymentRequest() - - assert args[0] == request_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_export_lock_info_empty_call_grpc(): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.export_lock_info), - '__call__') as call: - call.return_value = config.LockInfo() - client.export_lock_info(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = config.ExportLockInfoRequest() - - assert args[0] == request_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_preview_empty_call_grpc(): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_preview), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_preview(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = config.CreatePreviewRequest() - - assert args[0] == request_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_preview_empty_call_grpc(): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_preview), - '__call__') as call: - call.return_value = config.Preview() - client.get_preview(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = config.GetPreviewRequest() - - assert args[0] == request_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_previews_empty_call_grpc(): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_previews), - '__call__') as call: - call.return_value = config.ListPreviewsResponse() - client.list_previews(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = config.ListPreviewsRequest() - - assert args[0] == request_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_preview_empty_call_grpc(): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_preview), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_preview(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = config.DeletePreviewRequest() - - assert args[0] == request_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_export_preview_result_empty_call_grpc(): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.export_preview_result), - '__call__') as call: - call.return_value = config.ExportPreviewResultResponse() - client.export_preview_result(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = config.ExportPreviewResultRequest() - - assert args[0] == request_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_terraform_versions_empty_call_grpc(): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_terraform_versions), - '__call__') as call: - call.return_value = config.ListTerraformVersionsResponse() - client.list_terraform_versions(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = config.ListTerraformVersionsRequest() - - assert args[0] == request_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_terraform_version_empty_call_grpc(): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_terraform_version), - '__call__') as call: - call.return_value = config.TerraformVersion() - client.get_terraform_version(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = config.GetTerraformVersionRequest() - - assert args[0] == request_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_changes_empty_call_grpc(): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_resource_changes), - '__call__') as call: - call.return_value = config.ListResourceChangesResponse() - client.list_resource_changes(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = config.ListResourceChangesRequest() - - assert args[0] == request_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_change_empty_call_grpc(): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_resource_change), - '__call__') as call: - call.return_value = config.ResourceChange() - client.get_resource_change(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = config.GetResourceChangeRequest() - - assert args[0] == request_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_drifts_empty_call_grpc(): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_resource_drifts), - '__call__') as call: - call.return_value = config.ListResourceDriftsResponse() - client.list_resource_drifts(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = config.ListResourceDriftsRequest() - - assert args[0] == request_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_drift_empty_call_grpc(): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_resource_drift), - '__call__') as call: - call.return_value = config.ResourceDrift() - client.get_resource_drift(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = config.GetResourceDriftRequest() - - assert args[0] == request_msg - - -def test_transport_kind_grpc_asyncio(): - transport = ConfigAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" - - -def test_initialize_client_w_grpc_asyncio(): - client = ConfigAsyncClient( - 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_deployments_empty_call_grpc_asyncio(): - client = ConfigAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_deployments), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.ListDeploymentsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - )) - await client.list_deployments(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = config.ListDeploymentsRequest() - - assert args[0] == request_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_deployment_empty_call_grpc_asyncio(): - client = ConfigAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_deployment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.Deployment( - name='name_value', - state=config.Deployment.State.CREATING, - latest_revision='latest_revision_value', - state_detail='state_detail_value', - error_code=config.Deployment.ErrorCode.REVISION_FAILED, - delete_build='delete_build_value', - delete_logs='delete_logs_value', - error_logs='error_logs_value', - artifacts_gcs_bucket='artifacts_gcs_bucket_value', - service_account='service_account_value', - import_existing_resources=True, - worker_pool='worker_pool_value', - lock_state=config.Deployment.LockState.LOCKED, - tf_version_constraint='tf_version_constraint_value', - tf_version='tf_version_value', - quota_validation=config.QuotaValidation.ENABLED, - )) - await client.get_deployment(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = config.GetDeploymentRequest() - - assert args[0] == request_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_deployment_empty_call_grpc_asyncio(): - client = ConfigAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_deployment), - '__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_deployment(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = config.CreateDeploymentRequest() - - assert args[0] == request_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_deployment_empty_call_grpc_asyncio(): - client = ConfigAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_deployment), - '__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_deployment(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = config.UpdateDeploymentRequest() - - assert args[0] == request_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_deployment_empty_call_grpc_asyncio(): - client = ConfigAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_deployment), - '__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_deployment(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = config.DeleteDeploymentRequest() - - assert args[0] == request_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_revisions_empty_call_grpc_asyncio(): - client = ConfigAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_revisions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.ListRevisionsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - )) - await client.list_revisions(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = config.ListRevisionsRequest() - - assert args[0] == request_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_revision_empty_call_grpc_asyncio(): - client = ConfigAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_revision), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.Revision( - name='name_value', - action=config.Revision.Action.CREATE, - state=config.Revision.State.APPLYING, - state_detail='state_detail_value', - error_code=config.Revision.ErrorCode.CLOUD_BUILD_PERMISSION_DENIED, - build='build_value', - logs='logs_value', - error_logs='error_logs_value', - service_account='service_account_value', - import_existing_resources=True, - worker_pool='worker_pool_value', - tf_version_constraint='tf_version_constraint_value', - tf_version='tf_version_value', - quota_validation_results='quota_validation_results_value', - quota_validation=config.QuotaValidation.ENABLED, - )) - await client.get_revision(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = config.GetRevisionRequest() - - assert args[0] == request_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_empty_call_grpc_asyncio(): - client = ConfigAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_resource), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.Resource( - name='name_value', - intent=config.Resource.Intent.CREATE, - state=config.Resource.State.PLANNED, - )) - await client.get_resource(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = config.GetResourceRequest() - - assert args[0] == request_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_resources_empty_call_grpc_asyncio(): - client = ConfigAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_resources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.ListResourcesResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - )) - await client.list_resources(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = config.ListResourcesRequest() - - assert args[0] == request_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_export_deployment_statefile_empty_call_grpc_asyncio(): - client = ConfigAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.export_deployment_statefile), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.Statefile( - signed_uri='signed_uri_value', - )) - await client.export_deployment_statefile(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = config.ExportDeploymentStatefileRequest() - - assert args[0] == request_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_export_revision_statefile_empty_call_grpc_asyncio(): - client = ConfigAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.export_revision_statefile), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.Statefile( - signed_uri='signed_uri_value', - )) - await client.export_revision_statefile(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = config.ExportRevisionStatefileRequest() - - assert args[0] == request_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_import_statefile_empty_call_grpc_asyncio(): - client = ConfigAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.import_statefile), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.Statefile( - signed_uri='signed_uri_value', - )) - await client.import_statefile(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = config.ImportStatefileRequest() - - assert args[0] == request_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_statefile_empty_call_grpc_asyncio(): - client = ConfigAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_statefile), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_statefile(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = config.DeleteStatefileRequest() - - assert args[0] == request_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_lock_deployment_empty_call_grpc_asyncio(): - client = ConfigAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.lock_deployment), - '__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.lock_deployment(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = config.LockDeploymentRequest() - - assert args[0] == request_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_unlock_deployment_empty_call_grpc_asyncio(): - client = ConfigAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.unlock_deployment), - '__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.unlock_deployment(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = config.UnlockDeploymentRequest() - - assert args[0] == request_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_export_lock_info_empty_call_grpc_asyncio(): - client = ConfigAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.export_lock_info), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.LockInfo( - lock_id=725, - operation='operation_value', - info='info_value', - who='who_value', - version='version_value', - )) - await client.export_lock_info(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = config.ExportLockInfoRequest() - - assert args[0] == request_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_preview_empty_call_grpc_asyncio(): - client = ConfigAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_preview), - '__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_preview(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = config.CreatePreviewRequest() - - assert args[0] == request_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_preview_empty_call_grpc_asyncio(): - client = ConfigAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_preview), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.Preview( - name='name_value', - state=config.Preview.State.CREATING, - deployment='deployment_value', - preview_mode=config.Preview.PreviewMode.DEFAULT, - service_account='service_account_value', - artifacts_gcs_bucket='artifacts_gcs_bucket_value', - worker_pool='worker_pool_value', - error_code=config.Preview.ErrorCode.CLOUD_BUILD_PERMISSION_DENIED, - build='build_value', - error_logs='error_logs_value', - logs='logs_value', - tf_version='tf_version_value', - tf_version_constraint='tf_version_constraint_value', - )) - await client.get_preview(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = config.GetPreviewRequest() - - assert args[0] == request_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_previews_empty_call_grpc_asyncio(): - client = ConfigAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_previews), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.ListPreviewsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - )) - await client.list_previews(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = config.ListPreviewsRequest() - - assert args[0] == request_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_preview_empty_call_grpc_asyncio(): - client = ConfigAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_preview), - '__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_preview(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = config.DeletePreviewRequest() - - assert args[0] == request_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_export_preview_result_empty_call_grpc_asyncio(): - client = ConfigAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.export_preview_result), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.ExportPreviewResultResponse( - )) - await client.export_preview_result(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = config.ExportPreviewResultRequest() - - assert args[0] == request_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_terraform_versions_empty_call_grpc_asyncio(): - client = ConfigAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_terraform_versions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.ListTerraformVersionsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - )) - await client.list_terraform_versions(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = config.ListTerraformVersionsRequest() - - assert args[0] == request_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_terraform_version_empty_call_grpc_asyncio(): - client = ConfigAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_terraform_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.TerraformVersion( - name='name_value', - state=config.TerraformVersion.State.ACTIVE, - )) - await client.get_terraform_version(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = config.GetTerraformVersionRequest() - - assert args[0] == request_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_changes_empty_call_grpc_asyncio(): - client = ConfigAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_resource_changes), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.ListResourceChangesResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - )) - await client.list_resource_changes(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = config.ListResourceChangesRequest() - - assert args[0] == request_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_change_empty_call_grpc_asyncio(): - client = ConfigAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_resource_change), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.ResourceChange( - name='name_value', - intent=config.ResourceChange.Intent.CREATE, - )) - await client.get_resource_change(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = config.GetResourceChangeRequest() - - assert args[0] == request_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_drifts_empty_call_grpc_asyncio(): - client = ConfigAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_resource_drifts), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.ListResourceDriftsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - )) - await client.list_resource_drifts(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = config.ListResourceDriftsRequest() - - assert args[0] == request_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_drift_empty_call_grpc_asyncio(): - client = ConfigAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_resource_drift), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(config.ResourceDrift( - name='name_value', - )) - await client.get_resource_drift(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = config.GetResourceDriftRequest() - - assert args[0] == request_msg - - -def test_transport_kind_rest(): - transport = ConfigClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" - - -def test_list_deployments_rest_bad_request(request_type=config.ListDeploymentsRequest): - client = ConfigClient( - 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_deployments(request) - - -@pytest.mark.parametrize("request_type", [ - config.ListDeploymentsRequest, - dict, -]) -def test_list_deployments_rest_call_success(request_type): - client = ConfigClient( - 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 = config.ListDeploymentsResponse( - 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 = config.ListDeploymentsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_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_deployments(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListDeploymentsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_deployments_rest_interceptors(null_interceptor): - transport = transports.ConfigRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ConfigRestInterceptor(), - ) - client = ConfigClient(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.ConfigRestInterceptor, "post_list_deployments") as post, \ - mock.patch.object(transports.ConfigRestInterceptor, "post_list_deployments_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.ConfigRestInterceptor, "pre_list_deployments") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = config.ListDeploymentsRequest.pb(config.ListDeploymentsRequest()) - 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 = config.ListDeploymentsResponse.to_json(config.ListDeploymentsResponse()) - req.return_value.content = return_value - - request = config.ListDeploymentsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = config.ListDeploymentsResponse() - post_with_metadata.return_value = config.ListDeploymentsResponse(), metadata - - client.list_deployments(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_get_deployment_rest_bad_request(request_type=config.GetDeploymentRequest): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/deployments/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_deployment(request) - - -@pytest.mark.parametrize("request_type", [ - config.GetDeploymentRequest, - dict, -]) -def test_get_deployment_rest_call_success(request_type): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/deployments/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 = config.Deployment( - name='name_value', - state=config.Deployment.State.CREATING, - latest_revision='latest_revision_value', - state_detail='state_detail_value', - error_code=config.Deployment.ErrorCode.REVISION_FAILED, - delete_build='delete_build_value', - delete_logs='delete_logs_value', - error_logs='error_logs_value', - artifacts_gcs_bucket='artifacts_gcs_bucket_value', - service_account='service_account_value', - import_existing_resources=True, - worker_pool='worker_pool_value', - lock_state=config.Deployment.LockState.LOCKED, - tf_version_constraint='tf_version_constraint_value', - tf_version='tf_version_value', - quota_validation=config.QuotaValidation.ENABLED, - ) - - # 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 = config.Deployment.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_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_deployment(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, config.Deployment) - assert response.name == 'name_value' - assert response.state == config.Deployment.State.CREATING - assert response.latest_revision == 'latest_revision_value' - assert response.state_detail == 'state_detail_value' - assert response.error_code == config.Deployment.ErrorCode.REVISION_FAILED - assert response.delete_build == 'delete_build_value' - assert response.delete_logs == 'delete_logs_value' - assert response.error_logs == 'error_logs_value' - assert response.artifacts_gcs_bucket == 'artifacts_gcs_bucket_value' - assert response.service_account == 'service_account_value' - assert response.import_existing_resources is True - assert response.worker_pool == 'worker_pool_value' - assert response.lock_state == config.Deployment.LockState.LOCKED - assert response.tf_version_constraint == 'tf_version_constraint_value' - assert response.tf_version == 'tf_version_value' - assert response.quota_validation == config.QuotaValidation.ENABLED - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_deployment_rest_interceptors(null_interceptor): - transport = transports.ConfigRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ConfigRestInterceptor(), - ) - client = ConfigClient(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.ConfigRestInterceptor, "post_get_deployment") as post, \ - mock.patch.object(transports.ConfigRestInterceptor, "post_get_deployment_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.ConfigRestInterceptor, "pre_get_deployment") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = config.GetDeploymentRequest.pb(config.GetDeploymentRequest()) - 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 = config.Deployment.to_json(config.Deployment()) - req.return_value.content = return_value - - request = config.GetDeploymentRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = config.Deployment() - post_with_metadata.return_value = config.Deployment(), metadata - - client.get_deployment(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_create_deployment_rest_bad_request(request_type=config.CreateDeploymentRequest): - client = ConfigClient( - 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_deployment(request) - - -@pytest.mark.parametrize("request_type", [ - config.CreateDeploymentRequest, - dict, -]) -def test_create_deployment_rest_call_success(request_type): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request_init["deployment"] = {'terraform_blueprint': {'gcs_source': 'gcs_source_value', 'git_source': {'repo': 'repo_value', 'directory': 'directory_value', 'ref': 'ref_value'}, 'input_values': {}}, 'name': 'name_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'state': 1, 'latest_revision': 'latest_revision_value', 'state_detail': 'state_detail_value', 'error_code': 1, 'delete_results': {'content': 'content_value', 'artifacts': 'artifacts_value', 'outputs': {}}, 'delete_build': 'delete_build_value', 'delete_logs': 'delete_logs_value', 'tf_errors': [{'resource_address': 'resource_address_value', 'http_response_code': 1928, 'error_description': 'error_description_value', 'error': {'code': 411, 'message': 'message_value', 'details': [{'type_url': 'type.googleapis.com/google.protobuf.Duration', 'value': b'\x08\x0c\x10\xdb\x07'}]}}], 'error_logs': 'error_logs_value', 'artifacts_gcs_bucket': 'artifacts_gcs_bucket_value', 'service_account': 'service_account_value', 'import_existing_resources': True, 'worker_pool': 'worker_pool_value', 'lock_state': 1, 'tf_version_constraint': 'tf_version_constraint_value', 'tf_version': 'tf_version_value', 'quota_validation': 1, 'annotations': {}, 'provider_config': {'source_type': 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 = config.CreateDeploymentRequest.meta.fields["deployment"] - - 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["deployment"].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["deployment"][field])): - del request_init["deployment"][field][i][subfield] - else: - del request_init["deployment"][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_deployment(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_deployment_rest_interceptors(null_interceptor): - transport = transports.ConfigRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ConfigRestInterceptor(), - ) - client = ConfigClient(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.ConfigRestInterceptor, "post_create_deployment") as post, \ - mock.patch.object(transports.ConfigRestInterceptor, "post_create_deployment_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.ConfigRestInterceptor, "pre_create_deployment") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = config.CreateDeploymentRequest.pb(config.CreateDeploymentRequest()) - 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 = config.CreateDeploymentRequest() - 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_deployment(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_update_deployment_rest_bad_request(request_type=config.UpdateDeploymentRequest): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'deployment': {'name': 'projects/sample1/locations/sample2/deployments/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_deployment(request) - - -@pytest.mark.parametrize("request_type", [ - config.UpdateDeploymentRequest, - dict, -]) -def test_update_deployment_rest_call_success(request_type): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'deployment': {'name': 'projects/sample1/locations/sample2/deployments/sample3'}} - request_init["deployment"] = {'terraform_blueprint': {'gcs_source': 'gcs_source_value', 'git_source': {'repo': 'repo_value', 'directory': 'directory_value', 'ref': 'ref_value'}, 'input_values': {}}, 'name': 'projects/sample1/locations/sample2/deployments/sample3', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'state': 1, 'latest_revision': 'latest_revision_value', 'state_detail': 'state_detail_value', 'error_code': 1, 'delete_results': {'content': 'content_value', 'artifacts': 'artifacts_value', 'outputs': {}}, 'delete_build': 'delete_build_value', 'delete_logs': 'delete_logs_value', 'tf_errors': [{'resource_address': 'resource_address_value', 'http_response_code': 1928, 'error_description': 'error_description_value', 'error': {'code': 411, 'message': 'message_value', 'details': [{'type_url': 'type.googleapis.com/google.protobuf.Duration', 'value': b'\x08\x0c\x10\xdb\x07'}]}}], 'error_logs': 'error_logs_value', 'artifacts_gcs_bucket': 'artifacts_gcs_bucket_value', 'service_account': 'service_account_value', 'import_existing_resources': True, 'worker_pool': 'worker_pool_value', 'lock_state': 1, 'tf_version_constraint': 'tf_version_constraint_value', 'tf_version': 'tf_version_value', 'quota_validation': 1, 'annotations': {}, 'provider_config': {'source_type': 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 = config.UpdateDeploymentRequest.meta.fields["deployment"] - - 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["deployment"].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["deployment"][field])): - del request_init["deployment"][field][i][subfield] - else: - del request_init["deployment"][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_deployment(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_deployment_rest_interceptors(null_interceptor): - transport = transports.ConfigRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ConfigRestInterceptor(), - ) - client = ConfigClient(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.ConfigRestInterceptor, "post_update_deployment") as post, \ - mock.patch.object(transports.ConfigRestInterceptor, "post_update_deployment_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.ConfigRestInterceptor, "pre_update_deployment") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = config.UpdateDeploymentRequest.pb(config.UpdateDeploymentRequest()) - 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 = config.UpdateDeploymentRequest() - 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_deployment(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_delete_deployment_rest_bad_request(request_type=config.DeleteDeploymentRequest): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/deployments/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_deployment(request) - - -@pytest.mark.parametrize("request_type", [ - config.DeleteDeploymentRequest, - dict, -]) -def test_delete_deployment_rest_call_success(request_type): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/deployments/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_deployment(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_deployment_rest_interceptors(null_interceptor): - transport = transports.ConfigRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ConfigRestInterceptor(), - ) - client = ConfigClient(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.ConfigRestInterceptor, "post_delete_deployment") as post, \ - mock.patch.object(transports.ConfigRestInterceptor, "post_delete_deployment_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.ConfigRestInterceptor, "pre_delete_deployment") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = config.DeleteDeploymentRequest.pb(config.DeleteDeploymentRequest()) - 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 = config.DeleteDeploymentRequest() - 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_deployment(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_list_revisions_rest_bad_request(request_type=config.ListRevisionsRequest): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/deployments/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_revisions(request) - - -@pytest.mark.parametrize("request_type", [ - config.ListRevisionsRequest, - dict, -]) -def test_list_revisions_rest_call_success(request_type): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/deployments/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 = config.ListRevisionsResponse( - 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 = config.ListRevisionsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_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_revisions(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListRevisionsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_revisions_rest_interceptors(null_interceptor): - transport = transports.ConfigRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ConfigRestInterceptor(), - ) - client = ConfigClient(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.ConfigRestInterceptor, "post_list_revisions") as post, \ - mock.patch.object(transports.ConfigRestInterceptor, "post_list_revisions_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.ConfigRestInterceptor, "pre_list_revisions") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = config.ListRevisionsRequest.pb(config.ListRevisionsRequest()) - 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 = config.ListRevisionsResponse.to_json(config.ListRevisionsResponse()) - req.return_value.content = return_value - - request = config.ListRevisionsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = config.ListRevisionsResponse() - post_with_metadata.return_value = config.ListRevisionsResponse(), metadata - - client.list_revisions(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_get_revision_rest_bad_request(request_type=config.GetRevisionRequest): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/deployments/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_revision(request) - - -@pytest.mark.parametrize("request_type", [ - config.GetRevisionRequest, - dict, -]) -def test_get_revision_rest_call_success(request_type): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/deployments/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 = config.Revision( - name='name_value', - action=config.Revision.Action.CREATE, - state=config.Revision.State.APPLYING, - state_detail='state_detail_value', - error_code=config.Revision.ErrorCode.CLOUD_BUILD_PERMISSION_DENIED, - build='build_value', - logs='logs_value', - error_logs='error_logs_value', - service_account='service_account_value', - import_existing_resources=True, - worker_pool='worker_pool_value', - tf_version_constraint='tf_version_constraint_value', - tf_version='tf_version_value', - quota_validation_results='quota_validation_results_value', - quota_validation=config.QuotaValidation.ENABLED, - ) - - # 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 = config.Revision.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_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_revision(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, config.Revision) - assert response.name == 'name_value' - assert response.action == config.Revision.Action.CREATE - assert response.state == config.Revision.State.APPLYING - assert response.state_detail == 'state_detail_value' - assert response.error_code == config.Revision.ErrorCode.CLOUD_BUILD_PERMISSION_DENIED - assert response.build == 'build_value' - assert response.logs == 'logs_value' - assert response.error_logs == 'error_logs_value' - assert response.service_account == 'service_account_value' - assert response.import_existing_resources is True - assert response.worker_pool == 'worker_pool_value' - assert response.tf_version_constraint == 'tf_version_constraint_value' - assert response.tf_version == 'tf_version_value' - assert response.quota_validation_results == 'quota_validation_results_value' - assert response.quota_validation == config.QuotaValidation.ENABLED - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_revision_rest_interceptors(null_interceptor): - transport = transports.ConfigRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ConfigRestInterceptor(), - ) - client = ConfigClient(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.ConfigRestInterceptor, "post_get_revision") as post, \ - mock.patch.object(transports.ConfigRestInterceptor, "post_get_revision_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.ConfigRestInterceptor, "pre_get_revision") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = config.GetRevisionRequest.pb(config.GetRevisionRequest()) - 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 = config.Revision.to_json(config.Revision()) - req.return_value.content = return_value - - request = config.GetRevisionRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = config.Revision() - post_with_metadata.return_value = config.Revision(), metadata - - client.get_revision(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_get_resource_rest_bad_request(request_type=config.GetResourceRequest): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/deployments/sample3/revisions/sample4/resources/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_resource(request) - - -@pytest.mark.parametrize("request_type", [ - config.GetResourceRequest, - dict, -]) -def test_get_resource_rest_call_success(request_type): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/deployments/sample3/revisions/sample4/resources/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 = config.Resource( - name='name_value', - intent=config.Resource.Intent.CREATE, - state=config.Resource.State.PLANNED, - ) - - # 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 = config.Resource.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_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(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, config.Resource) - assert response.name == 'name_value' - assert response.intent == config.Resource.Intent.CREATE - assert response.state == config.Resource.State.PLANNED - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_resource_rest_interceptors(null_interceptor): - transport = transports.ConfigRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ConfigRestInterceptor(), - ) - client = ConfigClient(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.ConfigRestInterceptor, "post_get_resource") as post, \ - mock.patch.object(transports.ConfigRestInterceptor, "post_get_resource_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.ConfigRestInterceptor, "pre_get_resource") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = config.GetResourceRequest.pb(config.GetResourceRequest()) - 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 = config.Resource.to_json(config.Resource()) - req.return_value.content = return_value - - request = config.GetResourceRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = config.Resource() - post_with_metadata.return_value = config.Resource(), metadata - - client.get_resource(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_list_resources_rest_bad_request(request_type=config.ListResourcesRequest): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/deployments/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.list_resources(request) - - -@pytest.mark.parametrize("request_type", [ - config.ListResourcesRequest, - dict, -]) -def test_list_resources_rest_call_success(request_type): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/deployments/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 = config.ListResourcesResponse( - 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 = config.ListResourcesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_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_resources(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListResourcesPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_resources_rest_interceptors(null_interceptor): - transport = transports.ConfigRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ConfigRestInterceptor(), - ) - client = ConfigClient(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.ConfigRestInterceptor, "post_list_resources") as post, \ - mock.patch.object(transports.ConfigRestInterceptor, "post_list_resources_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.ConfigRestInterceptor, "pre_list_resources") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = config.ListResourcesRequest.pb(config.ListResourcesRequest()) - 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 = config.ListResourcesResponse.to_json(config.ListResourcesResponse()) - req.return_value.content = return_value - - request = config.ListResourcesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = config.ListResourcesResponse() - post_with_metadata.return_value = config.ListResourcesResponse(), metadata - - client.list_resources(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_export_deployment_statefile_rest_bad_request(request_type=config.ExportDeploymentStatefileRequest): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/deployments/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.export_deployment_statefile(request) - - -@pytest.mark.parametrize("request_type", [ - config.ExportDeploymentStatefileRequest, - dict, -]) -def test_export_deployment_statefile_rest_call_success(request_type): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/deployments/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 = config.Statefile( - signed_uri='signed_uri_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 = config.Statefile.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.export_deployment_statefile(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, config.Statefile) - assert response.signed_uri == 'signed_uri_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_export_deployment_statefile_rest_interceptors(null_interceptor): - transport = transports.ConfigRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ConfigRestInterceptor(), - ) - client = ConfigClient(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.ConfigRestInterceptor, "post_export_deployment_statefile") as post, \ - mock.patch.object(transports.ConfigRestInterceptor, "post_export_deployment_statefile_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.ConfigRestInterceptor, "pre_export_deployment_statefile") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = config.ExportDeploymentStatefileRequest.pb(config.ExportDeploymentStatefileRequest()) - 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 = config.Statefile.to_json(config.Statefile()) - req.return_value.content = return_value - - request = config.ExportDeploymentStatefileRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = config.Statefile() - post_with_metadata.return_value = config.Statefile(), metadata - - client.export_deployment_statefile(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_export_revision_statefile_rest_bad_request(request_type=config.ExportRevisionStatefileRequest): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/deployments/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.export_revision_statefile(request) - - -@pytest.mark.parametrize("request_type", [ - config.ExportRevisionStatefileRequest, - dict, -]) -def test_export_revision_statefile_rest_call_success(request_type): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/deployments/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 = config.Statefile( - signed_uri='signed_uri_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 = config.Statefile.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.export_revision_statefile(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, config.Statefile) - assert response.signed_uri == 'signed_uri_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_export_revision_statefile_rest_interceptors(null_interceptor): - transport = transports.ConfigRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ConfigRestInterceptor(), - ) - client = ConfigClient(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.ConfigRestInterceptor, "post_export_revision_statefile") as post, \ - mock.patch.object(transports.ConfigRestInterceptor, "post_export_revision_statefile_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.ConfigRestInterceptor, "pre_export_revision_statefile") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = config.ExportRevisionStatefileRequest.pb(config.ExportRevisionStatefileRequest()) - 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 = config.Statefile.to_json(config.Statefile()) - req.return_value.content = return_value - - request = config.ExportRevisionStatefileRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = config.Statefile() - post_with_metadata.return_value = config.Statefile(), metadata - - client.export_revision_statefile(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_import_statefile_rest_bad_request(request_type=config.ImportStatefileRequest): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/deployments/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.import_statefile(request) - - -@pytest.mark.parametrize("request_type", [ - config.ImportStatefileRequest, - dict, -]) -def test_import_statefile_rest_call_success(request_type): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/deployments/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 = config.Statefile( - signed_uri='signed_uri_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 = config.Statefile.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.import_statefile(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, config.Statefile) - assert response.signed_uri == 'signed_uri_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_import_statefile_rest_interceptors(null_interceptor): - transport = transports.ConfigRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ConfigRestInterceptor(), - ) - client = ConfigClient(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.ConfigRestInterceptor, "post_import_statefile") as post, \ - mock.patch.object(transports.ConfigRestInterceptor, "post_import_statefile_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.ConfigRestInterceptor, "pre_import_statefile") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = config.ImportStatefileRequest.pb(config.ImportStatefileRequest()) - 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 = config.Statefile.to_json(config.Statefile()) - req.return_value.content = return_value - - request = config.ImportStatefileRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = config.Statefile() - post_with_metadata.return_value = config.Statefile(), metadata - - client.import_statefile(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_delete_statefile_rest_bad_request(request_type=config.DeleteStatefileRequest): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/deployments/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_statefile(request) - - -@pytest.mark.parametrize("request_type", [ - config.DeleteStatefileRequest, - dict, -]) -def test_delete_statefile_rest_call_success(request_type): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/deployments/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 - - # 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_statefile(request) - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_statefile_rest_interceptors(null_interceptor): - transport = transports.ConfigRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ConfigRestInterceptor(), - ) - client = ConfigClient(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.ConfigRestInterceptor, "pre_delete_statefile") as pre: - pre.assert_not_called() - pb_message = config.DeleteStatefileRequest.pb(config.DeleteStatefileRequest()) - 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"} - - request = config.DeleteStatefileRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_statefile(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - - -def test_lock_deployment_rest_bad_request(request_type=config.LockDeploymentRequest): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/deployments/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.lock_deployment(request) - - -@pytest.mark.parametrize("request_type", [ - config.LockDeploymentRequest, - dict, -]) -def test_lock_deployment_rest_call_success(request_type): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/deployments/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.lock_deployment(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_lock_deployment_rest_interceptors(null_interceptor): - transport = transports.ConfigRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ConfigRestInterceptor(), - ) - client = ConfigClient(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.ConfigRestInterceptor, "post_lock_deployment") as post, \ - mock.patch.object(transports.ConfigRestInterceptor, "post_lock_deployment_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.ConfigRestInterceptor, "pre_lock_deployment") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = config.LockDeploymentRequest.pb(config.LockDeploymentRequest()) - 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 = config.LockDeploymentRequest() - 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.lock_deployment(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_unlock_deployment_rest_bad_request(request_type=config.UnlockDeploymentRequest): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/deployments/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.unlock_deployment(request) - - -@pytest.mark.parametrize("request_type", [ - config.UnlockDeploymentRequest, - dict, -]) -def test_unlock_deployment_rest_call_success(request_type): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/deployments/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.unlock_deployment(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_unlock_deployment_rest_interceptors(null_interceptor): - transport = transports.ConfigRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ConfigRestInterceptor(), - ) - client = ConfigClient(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.ConfigRestInterceptor, "post_unlock_deployment") as post, \ - mock.patch.object(transports.ConfigRestInterceptor, "post_unlock_deployment_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.ConfigRestInterceptor, "pre_unlock_deployment") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = config.UnlockDeploymentRequest.pb(config.UnlockDeploymentRequest()) - 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 = config.UnlockDeploymentRequest() - 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.unlock_deployment(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_export_lock_info_rest_bad_request(request_type=config.ExportLockInfoRequest): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/deployments/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.export_lock_info(request) - - -@pytest.mark.parametrize("request_type", [ - config.ExportLockInfoRequest, - dict, -]) -def test_export_lock_info_rest_call_success(request_type): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/deployments/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 = config.LockInfo( - lock_id=725, - operation='operation_value', - info='info_value', - who='who_value', - version='version_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 = config.LockInfo.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.export_lock_info(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, config.LockInfo) - assert response.lock_id == 725 - assert response.operation == 'operation_value' - assert response.info == 'info_value' - assert response.who == 'who_value' - assert response.version == 'version_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_export_lock_info_rest_interceptors(null_interceptor): - transport = transports.ConfigRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ConfigRestInterceptor(), - ) - client = ConfigClient(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.ConfigRestInterceptor, "post_export_lock_info") as post, \ - mock.patch.object(transports.ConfigRestInterceptor, "post_export_lock_info_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.ConfigRestInterceptor, "pre_export_lock_info") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = config.ExportLockInfoRequest.pb(config.ExportLockInfoRequest()) - 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 = config.LockInfo.to_json(config.LockInfo()) - req.return_value.content = return_value - - request = config.ExportLockInfoRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = config.LockInfo() - post_with_metadata.return_value = config.LockInfo(), metadata - - client.export_lock_info(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_create_preview_rest_bad_request(request_type=config.CreatePreviewRequest): - client = ConfigClient( - 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_preview(request) - - -@pytest.mark.parametrize("request_type", [ - config.CreatePreviewRequest, - dict, -]) -def test_create_preview_rest_call_success(request_type): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request_init["preview"] = {'terraform_blueprint': {'gcs_source': 'gcs_source_value', 'git_source': {'repo': 'repo_value', 'directory': 'directory_value', 'ref': 'ref_value'}, 'input_values': {}}, 'name': 'name_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'labels': {}, 'state': 1, 'deployment': 'deployment_value', 'preview_mode': 1, 'service_account': 'service_account_value', 'artifacts_gcs_bucket': 'artifacts_gcs_bucket_value', 'worker_pool': 'worker_pool_value', 'error_code': 1, 'error_status': {'code': 411, 'message': 'message_value', 'details': [{'type_url': 'type.googleapis.com/google.protobuf.Duration', 'value': b'\x08\x0c\x10\xdb\x07'}]}, 'build': 'build_value', 'tf_errors': [{'resource_address': 'resource_address_value', 'http_response_code': 1928, 'error_description': 'error_description_value', 'error': {}}], 'error_logs': 'error_logs_value', 'preview_artifacts': {'content': 'content_value', 'artifacts': 'artifacts_value'}, 'logs': 'logs_value', 'tf_version': 'tf_version_value', 'tf_version_constraint': 'tf_version_constraint_value', 'annotations': {}, 'provider_config': {'source_type': 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 = config.CreatePreviewRequest.meta.fields["preview"] - - 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["preview"].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["preview"][field])): - del request_init["preview"][field][i][subfield] - else: - del request_init["preview"][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_preview(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_preview_rest_interceptors(null_interceptor): - transport = transports.ConfigRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ConfigRestInterceptor(), - ) - client = ConfigClient(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.ConfigRestInterceptor, "post_create_preview") as post, \ - mock.patch.object(transports.ConfigRestInterceptor, "post_create_preview_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.ConfigRestInterceptor, "pre_create_preview") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = config.CreatePreviewRequest.pb(config.CreatePreviewRequest()) - 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 = config.CreatePreviewRequest() - 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_preview(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_get_preview_rest_bad_request(request_type=config.GetPreviewRequest): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/previews/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_preview(request) - - -@pytest.mark.parametrize("request_type", [ - config.GetPreviewRequest, - dict, -]) -def test_get_preview_rest_call_success(request_type): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/previews/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 = config.Preview( - name='name_value', - state=config.Preview.State.CREATING, - deployment='deployment_value', - preview_mode=config.Preview.PreviewMode.DEFAULT, - service_account='service_account_value', - artifacts_gcs_bucket='artifacts_gcs_bucket_value', - worker_pool='worker_pool_value', - error_code=config.Preview.ErrorCode.CLOUD_BUILD_PERMISSION_DENIED, - build='build_value', - error_logs='error_logs_value', - logs='logs_value', - tf_version='tf_version_value', - tf_version_constraint='tf_version_constraint_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 = config.Preview.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_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_preview(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, config.Preview) - assert response.name == 'name_value' - assert response.state == config.Preview.State.CREATING - assert response.deployment == 'deployment_value' - assert response.preview_mode == config.Preview.PreviewMode.DEFAULT - assert response.service_account == 'service_account_value' - assert response.artifacts_gcs_bucket == 'artifacts_gcs_bucket_value' - assert response.worker_pool == 'worker_pool_value' - assert response.error_code == config.Preview.ErrorCode.CLOUD_BUILD_PERMISSION_DENIED - assert response.build == 'build_value' - assert response.error_logs == 'error_logs_value' - assert response.logs == 'logs_value' - assert response.tf_version == 'tf_version_value' - assert response.tf_version_constraint == 'tf_version_constraint_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_preview_rest_interceptors(null_interceptor): - transport = transports.ConfigRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ConfigRestInterceptor(), - ) - client = ConfigClient(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.ConfigRestInterceptor, "post_get_preview") as post, \ - mock.patch.object(transports.ConfigRestInterceptor, "post_get_preview_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.ConfigRestInterceptor, "pre_get_preview") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = config.GetPreviewRequest.pb(config.GetPreviewRequest()) - 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 = config.Preview.to_json(config.Preview()) - req.return_value.content = return_value - - request = config.GetPreviewRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = config.Preview() - post_with_metadata.return_value = config.Preview(), metadata - - client.get_preview(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_list_previews_rest_bad_request(request_type=config.ListPreviewsRequest): - client = ConfigClient( - 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_previews(request) - - -@pytest.mark.parametrize("request_type", [ - config.ListPreviewsRequest, - dict, -]) -def test_list_previews_rest_call_success(request_type): - client = ConfigClient( - 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 = config.ListPreviewsResponse( - 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 = config.ListPreviewsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_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_previews(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListPreviewsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_previews_rest_interceptors(null_interceptor): - transport = transports.ConfigRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ConfigRestInterceptor(), - ) - client = ConfigClient(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.ConfigRestInterceptor, "post_list_previews") as post, \ - mock.patch.object(transports.ConfigRestInterceptor, "post_list_previews_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.ConfigRestInterceptor, "pre_list_previews") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = config.ListPreviewsRequest.pb(config.ListPreviewsRequest()) - 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 = config.ListPreviewsResponse.to_json(config.ListPreviewsResponse()) - req.return_value.content = return_value - - request = config.ListPreviewsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = config.ListPreviewsResponse() - post_with_metadata.return_value = config.ListPreviewsResponse(), metadata - - client.list_previews(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_delete_preview_rest_bad_request(request_type=config.DeletePreviewRequest): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/previews/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_preview(request) - - -@pytest.mark.parametrize("request_type", [ - config.DeletePreviewRequest, - dict, -]) -def test_delete_preview_rest_call_success(request_type): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/previews/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_preview(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_preview_rest_interceptors(null_interceptor): - transport = transports.ConfigRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ConfigRestInterceptor(), - ) - client = ConfigClient(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.ConfigRestInterceptor, "post_delete_preview") as post, \ - mock.patch.object(transports.ConfigRestInterceptor, "post_delete_preview_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.ConfigRestInterceptor, "pre_delete_preview") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = config.DeletePreviewRequest.pb(config.DeletePreviewRequest()) - 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 = config.DeletePreviewRequest() - 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_preview(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_export_preview_result_rest_bad_request(request_type=config.ExportPreviewResultRequest): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/previews/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.export_preview_result(request) - - -@pytest.mark.parametrize("request_type", [ - config.ExportPreviewResultRequest, - dict, -]) -def test_export_preview_result_rest_call_success(request_type): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/previews/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 = config.ExportPreviewResultResponse( - ) - - # 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 = config.ExportPreviewResultResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.export_preview_result(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, config.ExportPreviewResultResponse) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_export_preview_result_rest_interceptors(null_interceptor): - transport = transports.ConfigRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ConfigRestInterceptor(), - ) - client = ConfigClient(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.ConfigRestInterceptor, "post_export_preview_result") as post, \ - mock.patch.object(transports.ConfigRestInterceptor, "post_export_preview_result_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.ConfigRestInterceptor, "pre_export_preview_result") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = config.ExportPreviewResultRequest.pb(config.ExportPreviewResultRequest()) - 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 = config.ExportPreviewResultResponse.to_json(config.ExportPreviewResultResponse()) - req.return_value.content = return_value - - request = config.ExportPreviewResultRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = config.ExportPreviewResultResponse() - post_with_metadata.return_value = config.ExportPreviewResultResponse(), metadata - - client.export_preview_result(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_list_terraform_versions_rest_bad_request(request_type=config.ListTerraformVersionsRequest): - client = ConfigClient( - 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_terraform_versions(request) - - -@pytest.mark.parametrize("request_type", [ - config.ListTerraformVersionsRequest, - dict, -]) -def test_list_terraform_versions_rest_call_success(request_type): - client = ConfigClient( - 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 = config.ListTerraformVersionsResponse( - 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 = config.ListTerraformVersionsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_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_terraform_versions(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListTerraformVersionsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_terraform_versions_rest_interceptors(null_interceptor): - transport = transports.ConfigRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ConfigRestInterceptor(), - ) - client = ConfigClient(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.ConfigRestInterceptor, "post_list_terraform_versions") as post, \ - mock.patch.object(transports.ConfigRestInterceptor, "post_list_terraform_versions_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.ConfigRestInterceptor, "pre_list_terraform_versions") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = config.ListTerraformVersionsRequest.pb(config.ListTerraformVersionsRequest()) - 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 = config.ListTerraformVersionsResponse.to_json(config.ListTerraformVersionsResponse()) - req.return_value.content = return_value - - request = config.ListTerraformVersionsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = config.ListTerraformVersionsResponse() - post_with_metadata.return_value = config.ListTerraformVersionsResponse(), metadata - - client.list_terraform_versions(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_get_terraform_version_rest_bad_request(request_type=config.GetTerraformVersionRequest): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/terraformVersions/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_terraform_version(request) - - -@pytest.mark.parametrize("request_type", [ - config.GetTerraformVersionRequest, - dict, -]) -def test_get_terraform_version_rest_call_success(request_type): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/terraformVersions/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 = config.TerraformVersion( - name='name_value', - state=config.TerraformVersion.State.ACTIVE, - ) - - # 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 = config.TerraformVersion.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_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_terraform_version(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, config.TerraformVersion) - assert response.name == 'name_value' - assert response.state == config.TerraformVersion.State.ACTIVE - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_terraform_version_rest_interceptors(null_interceptor): - transport = transports.ConfigRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ConfigRestInterceptor(), - ) - client = ConfigClient(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.ConfigRestInterceptor, "post_get_terraform_version") as post, \ - mock.patch.object(transports.ConfigRestInterceptor, "post_get_terraform_version_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.ConfigRestInterceptor, "pre_get_terraform_version") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = config.GetTerraformVersionRequest.pb(config.GetTerraformVersionRequest()) - 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 = config.TerraformVersion.to_json(config.TerraformVersion()) - req.return_value.content = return_value - - request = config.GetTerraformVersionRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = config.TerraformVersion() - post_with_metadata.return_value = config.TerraformVersion(), metadata - - client.get_terraform_version(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_list_resource_changes_rest_bad_request(request_type=config.ListResourceChangesRequest): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/previews/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_resource_changes(request) - - -@pytest.mark.parametrize("request_type", [ - config.ListResourceChangesRequest, - dict, -]) -def test_list_resource_changes_rest_call_success(request_type): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/previews/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 = config.ListResourceChangesResponse( - 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 = config.ListResourceChangesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_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_changes(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListResourceChangesPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_resource_changes_rest_interceptors(null_interceptor): - transport = transports.ConfigRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ConfigRestInterceptor(), - ) - client = ConfigClient(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.ConfigRestInterceptor, "post_list_resource_changes") as post, \ - mock.patch.object(transports.ConfigRestInterceptor, "post_list_resource_changes_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.ConfigRestInterceptor, "pre_list_resource_changes") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = config.ListResourceChangesRequest.pb(config.ListResourceChangesRequest()) - 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 = config.ListResourceChangesResponse.to_json(config.ListResourceChangesResponse()) - req.return_value.content = return_value - - request = config.ListResourceChangesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = config.ListResourceChangesResponse() - post_with_metadata.return_value = config.ListResourceChangesResponse(), metadata - - client.list_resource_changes(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_get_resource_change_rest_bad_request(request_type=config.GetResourceChangeRequest): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/previews/sample3/resourceChanges/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_resource_change(request) - - -@pytest.mark.parametrize("request_type", [ - config.GetResourceChangeRequest, - dict, -]) -def test_get_resource_change_rest_call_success(request_type): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/previews/sample3/resourceChanges/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 = config.ResourceChange( - name='name_value', - intent=config.ResourceChange.Intent.CREATE, - ) - - # 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 = config.ResourceChange.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_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_change(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, config.ResourceChange) - assert response.name == 'name_value' - assert response.intent == config.ResourceChange.Intent.CREATE - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_resource_change_rest_interceptors(null_interceptor): - transport = transports.ConfigRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ConfigRestInterceptor(), - ) - client = ConfigClient(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.ConfigRestInterceptor, "post_get_resource_change") as post, \ - mock.patch.object(transports.ConfigRestInterceptor, "post_get_resource_change_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.ConfigRestInterceptor, "pre_get_resource_change") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = config.GetResourceChangeRequest.pb(config.GetResourceChangeRequest()) - 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 = config.ResourceChange.to_json(config.ResourceChange()) - req.return_value.content = return_value - - request = config.GetResourceChangeRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = config.ResourceChange() - post_with_metadata.return_value = config.ResourceChange(), metadata - - client.get_resource_change(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_list_resource_drifts_rest_bad_request(request_type=config.ListResourceDriftsRequest): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/previews/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_resource_drifts(request) - - -@pytest.mark.parametrize("request_type", [ - config.ListResourceDriftsRequest, - dict, -]) -def test_list_resource_drifts_rest_call_success(request_type): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/previews/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 = config.ListResourceDriftsResponse( - 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 = config.ListResourceDriftsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_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_drifts(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListResourceDriftsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_resource_drifts_rest_interceptors(null_interceptor): - transport = transports.ConfigRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ConfigRestInterceptor(), - ) - client = ConfigClient(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.ConfigRestInterceptor, "post_list_resource_drifts") as post, \ - mock.patch.object(transports.ConfigRestInterceptor, "post_list_resource_drifts_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.ConfigRestInterceptor, "pre_list_resource_drifts") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = config.ListResourceDriftsRequest.pb(config.ListResourceDriftsRequest()) - 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 = config.ListResourceDriftsResponse.to_json(config.ListResourceDriftsResponse()) - req.return_value.content = return_value - - request = config.ListResourceDriftsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = config.ListResourceDriftsResponse() - post_with_metadata.return_value = config.ListResourceDriftsResponse(), metadata - - client.list_resource_drifts(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_get_resource_drift_rest_bad_request(request_type=config.GetResourceDriftRequest): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/previews/sample3/resourceDrifts/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_resource_drift(request) - - -@pytest.mark.parametrize("request_type", [ - config.GetResourceDriftRequest, - dict, -]) -def test_get_resource_drift_rest_call_success(request_type): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/previews/sample3/resourceDrifts/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 = config.ResourceDrift( - 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 = config.ResourceDrift.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_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_drift(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, config.ResourceDrift) - assert response.name == 'name_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_resource_drift_rest_interceptors(null_interceptor): - transport = transports.ConfigRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ConfigRestInterceptor(), - ) - client = ConfigClient(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.ConfigRestInterceptor, "post_get_resource_drift") as post, \ - mock.patch.object(transports.ConfigRestInterceptor, "post_get_resource_drift_with_metadata") as post_with_metadata, \ - mock.patch.object(transports.ConfigRestInterceptor, "pre_get_resource_drift") as pre: - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = config.GetResourceDriftRequest.pb(config.GetResourceDriftRequest()) - 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 = config.ResourceDrift.to_json(config.ResourceDrift()) - req.return_value.content = return_value - - request = config.GetResourceDriftRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = config.ResourceDrift() - post_with_metadata.return_value = config.ResourceDrift(), metadata - - client.get_resource_drift(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 = ConfigClient( - 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 = ConfigClient( - 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 = ConfigClient( - 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 = ConfigClient( - 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 = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/deployments/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 = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'resource': 'projects/sample1/locations/sample2/deployments/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 = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/deployments/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 = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'resource': 'projects/sample1/locations/sample2/deployments/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 = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/deployments/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 = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'resource': 'projects/sample1/locations/sample2/deployments/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 = ConfigClient( - 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 = ConfigClient( - 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 = ConfigClient( - 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 = ConfigClient( - 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 = ConfigClient( - 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 = ConfigClient( - 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 = ConfigClient( - 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 = ConfigClient( - 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 = ConfigClient( - 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_deployments_empty_call_rest(): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_deployments), - '__call__') as call: - client.list_deployments(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = config.ListDeploymentsRequest() - - assert args[0] == request_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_deployment_empty_call_rest(): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_deployment), - '__call__') as call: - client.get_deployment(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = config.GetDeploymentRequest() - - assert args[0] == request_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_deployment_empty_call_rest(): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_deployment), - '__call__') as call: - client.create_deployment(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = config.CreateDeploymentRequest() - - assert args[0] == request_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_deployment_empty_call_rest(): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_deployment), - '__call__') as call: - client.update_deployment(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = config.UpdateDeploymentRequest() - - assert args[0] == request_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_deployment_empty_call_rest(): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_deployment), - '__call__') as call: - client.delete_deployment(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = config.DeleteDeploymentRequest() - - assert args[0] == request_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_revisions_empty_call_rest(): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_revisions), - '__call__') as call: - client.list_revisions(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = config.ListRevisionsRequest() - - assert args[0] == request_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_revision_empty_call_rest(): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_revision), - '__call__') as call: - client.get_revision(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = config.GetRevisionRequest() - - assert args[0] == request_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_empty_call_rest(): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_resource), - '__call__') as call: - client.get_resource(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = config.GetResourceRequest() - - assert args[0] == request_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_resources_empty_call_rest(): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_resources), - '__call__') as call: - client.list_resources(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = config.ListResourcesRequest() - - assert args[0] == request_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_export_deployment_statefile_empty_call_rest(): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.export_deployment_statefile), - '__call__') as call: - client.export_deployment_statefile(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = config.ExportDeploymentStatefileRequest() - - assert args[0] == request_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_export_revision_statefile_empty_call_rest(): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.export_revision_statefile), - '__call__') as call: - client.export_revision_statefile(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = config.ExportRevisionStatefileRequest() - - assert args[0] == request_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_import_statefile_empty_call_rest(): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.import_statefile), - '__call__') as call: - client.import_statefile(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = config.ImportStatefileRequest() - - assert args[0] == request_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_statefile_empty_call_rest(): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_statefile), - '__call__') as call: - client.delete_statefile(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = config.DeleteStatefileRequest() - - assert args[0] == request_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_lock_deployment_empty_call_rest(): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.lock_deployment), - '__call__') as call: - client.lock_deployment(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = config.LockDeploymentRequest() - - assert args[0] == request_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_unlock_deployment_empty_call_rest(): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.unlock_deployment), - '__call__') as call: - client.unlock_deployment(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = config.UnlockDeploymentRequest() - - assert args[0] == request_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_export_lock_info_empty_call_rest(): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.export_lock_info), - '__call__') as call: - client.export_lock_info(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = config.ExportLockInfoRequest() - - assert args[0] == request_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_preview_empty_call_rest(): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_preview), - '__call__') as call: - client.create_preview(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = config.CreatePreviewRequest() - - assert args[0] == request_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_preview_empty_call_rest(): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_preview), - '__call__') as call: - client.get_preview(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = config.GetPreviewRequest() - - assert args[0] == request_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_previews_empty_call_rest(): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_previews), - '__call__') as call: - client.list_previews(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = config.ListPreviewsRequest() - - assert args[0] == request_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_preview_empty_call_rest(): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_preview), - '__call__') as call: - client.delete_preview(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = config.DeletePreviewRequest() - - assert args[0] == request_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_export_preview_result_empty_call_rest(): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.export_preview_result), - '__call__') as call: - client.export_preview_result(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = config.ExportPreviewResultRequest() - - assert args[0] == request_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_terraform_versions_empty_call_rest(): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_terraform_versions), - '__call__') as call: - client.list_terraform_versions(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = config.ListTerraformVersionsRequest() - - assert args[0] == request_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_terraform_version_empty_call_rest(): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_terraform_version), - '__call__') as call: - client.get_terraform_version(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = config.GetTerraformVersionRequest() - - assert args[0] == request_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_changes_empty_call_rest(): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_resource_changes), - '__call__') as call: - client.list_resource_changes(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = config.ListResourceChangesRequest() - - assert args[0] == request_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_change_empty_call_rest(): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_resource_change), - '__call__') as call: - client.get_resource_change(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = config.GetResourceChangeRequest() - - assert args[0] == request_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_drifts_empty_call_rest(): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_resource_drifts), - '__call__') as call: - client.list_resource_drifts(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = config.ListResourceDriftsRequest() - - assert args[0] == request_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_drift_empty_call_rest(): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_resource_drift), - '__call__') as call: - client.get_resource_drift(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = config.GetResourceDriftRequest() - - assert args[0] == request_msg - - -def test_config_rest_lro_client(): - client = ConfigClient( - 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 = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.ConfigGrpcTransport, - ) - -def test_config_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.ConfigTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_config_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.config_v1.services.config.transports.ConfigTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.ConfigTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'list_deployments', - 'get_deployment', - 'create_deployment', - 'update_deployment', - 'delete_deployment', - 'list_revisions', - 'get_revision', - 'get_resource', - 'list_resources', - 'export_deployment_statefile', - 'export_revision_statefile', - 'import_statefile', - 'delete_statefile', - 'lock_deployment', - 'unlock_deployment', - 'export_lock_info', - 'create_preview', - 'get_preview', - 'list_previews', - 'delete_preview', - 'export_preview_result', - 'list_terraform_versions', - 'get_terraform_version', - 'list_resource_changes', - 'get_resource_change', - 'list_resource_drifts', - 'get_resource_drift', - '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_config_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.config_v1.services.config.transports.ConfigTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ConfigTransport( - 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_config_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.config_v1.services.config.transports.ConfigTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ConfigTransport() - adc.assert_called_once() - - -def test_config_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) - ConfigClient() - 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.ConfigGrpcTransport, - transports.ConfigGrpcAsyncIOTransport, - ], -) -def test_config_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.ConfigGrpcTransport, - transports.ConfigGrpcAsyncIOTransport, - transports.ConfigRestTransport, - ], -) -def test_config_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.ConfigGrpcTransport, grpc_helpers), - (transports.ConfigGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_config_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( - "config.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="config.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.ConfigGrpcTransport, transports.ConfigGrpcAsyncIOTransport]) -def test_config_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_config_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.ConfigRestTransport ( - 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_config_host_no_port(transport_name): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='config.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'config.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://config.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_config_host_with_port(transport_name): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='config.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'config.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://config.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_config_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = ConfigClient( - credentials=creds1, - transport=transport_name, - ) - client2 = ConfigClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.list_deployments._session - session2 = client2.transport.list_deployments._session - assert session1 != session2 - session1 = client1.transport.get_deployment._session - session2 = client2.transport.get_deployment._session - assert session1 != session2 - session1 = client1.transport.create_deployment._session - session2 = client2.transport.create_deployment._session - assert session1 != session2 - session1 = client1.transport.update_deployment._session - session2 = client2.transport.update_deployment._session - assert session1 != session2 - session1 = client1.transport.delete_deployment._session - session2 = client2.transport.delete_deployment._session - assert session1 != session2 - session1 = client1.transport.list_revisions._session - session2 = client2.transport.list_revisions._session - assert session1 != session2 - session1 = client1.transport.get_revision._session - session2 = client2.transport.get_revision._session - assert session1 != session2 - session1 = client1.transport.get_resource._session - session2 = client2.transport.get_resource._session - assert session1 != session2 - session1 = client1.transport.list_resources._session - session2 = client2.transport.list_resources._session - assert session1 != session2 - session1 = client1.transport.export_deployment_statefile._session - session2 = client2.transport.export_deployment_statefile._session - assert session1 != session2 - session1 = client1.transport.export_revision_statefile._session - session2 = client2.transport.export_revision_statefile._session - assert session1 != session2 - session1 = client1.transport.import_statefile._session - session2 = client2.transport.import_statefile._session - assert session1 != session2 - session1 = client1.transport.delete_statefile._session - session2 = client2.transport.delete_statefile._session - assert session1 != session2 - session1 = client1.transport.lock_deployment._session - session2 = client2.transport.lock_deployment._session - assert session1 != session2 - session1 = client1.transport.unlock_deployment._session - session2 = client2.transport.unlock_deployment._session - assert session1 != session2 - session1 = client1.transport.export_lock_info._session - session2 = client2.transport.export_lock_info._session - assert session1 != session2 - session1 = client1.transport.create_preview._session - session2 = client2.transport.create_preview._session - assert session1 != session2 - session1 = client1.transport.get_preview._session - session2 = client2.transport.get_preview._session - assert session1 != session2 - session1 = client1.transport.list_previews._session - session2 = client2.transport.list_previews._session - assert session1 != session2 - session1 = client1.transport.delete_preview._session - session2 = client2.transport.delete_preview._session - assert session1 != session2 - session1 = client1.transport.export_preview_result._session - session2 = client2.transport.export_preview_result._session - assert session1 != session2 - session1 = client1.transport.list_terraform_versions._session - session2 = client2.transport.list_terraform_versions._session - assert session1 != session2 - session1 = client1.transport.get_terraform_version._session - session2 = client2.transport.get_terraform_version._session - assert session1 != session2 - session1 = client1.transport.list_resource_changes._session - session2 = client2.transport.list_resource_changes._session - assert session1 != session2 - session1 = client1.transport.get_resource_change._session - session2 = client2.transport.get_resource_change._session - assert session1 != session2 - session1 = client1.transport.list_resource_drifts._session - session2 = client2.transport.list_resource_drifts._session - assert session1 != session2 - session1 = client1.transport.get_resource_drift._session - session2 = client2.transport.get_resource_drift._session - assert session1 != session2 -def test_config_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ConfigGrpcTransport( - 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_config_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ConfigGrpcAsyncIOTransport( - 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.parametrize("transport_class", [transports.ConfigGrpcTransport, transports.ConfigGrpcAsyncIOTransport]) -def test_config_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.ConfigGrpcTransport, transports.ConfigGrpcAsyncIOTransport]) -def test_config_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_config_grpc_lro_client(): - client = ConfigClient( - 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_config_grpc_lro_async_client(): - client = ConfigAsyncClient( - 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_deployment_path(): - project = "squid" - location = "clam" - deployment = "whelk" - expected = "projects/{project}/locations/{location}/deployments/{deployment}".format(project=project, location=location, deployment=deployment, ) - actual = ConfigClient.deployment_path(project, location, deployment) - assert expected == actual - - -def test_parse_deployment_path(): - expected = { - "project": "octopus", - "location": "oyster", - "deployment": "nudibranch", - } - path = ConfigClient.deployment_path(**expected) - - # Check that the path construction is reversible. - actual = ConfigClient.parse_deployment_path(path) - assert expected == actual - -def test_preview_path(): - project = "cuttlefish" - location = "mussel" - preview = "winkle" - expected = "projects/{project}/locations/{location}/previews/{preview}".format(project=project, location=location, preview=preview, ) - actual = ConfigClient.preview_path(project, location, preview) - assert expected == actual - - -def test_parse_preview_path(): - expected = { - "project": "nautilus", - "location": "scallop", - "preview": "abalone", - } - path = ConfigClient.preview_path(**expected) - - # Check that the path construction is reversible. - actual = ConfigClient.parse_preview_path(path) - assert expected == actual - -def test_resource_path(): - project = "squid" - location = "clam" - deployment = "whelk" - revision = "octopus" - resource = "oyster" - expected = "projects/{project}/locations/{location}/deployments/{deployment}/revisions/{revision}/resources/{resource}".format(project=project, location=location, deployment=deployment, revision=revision, resource=resource, ) - actual = ConfigClient.resource_path(project, location, deployment, revision, resource) - assert expected == actual - - -def test_parse_resource_path(): - expected = { - "project": "nudibranch", - "location": "cuttlefish", - "deployment": "mussel", - "revision": "winkle", - "resource": "nautilus", - } - path = ConfigClient.resource_path(**expected) - - # Check that the path construction is reversible. - actual = ConfigClient.parse_resource_path(path) - assert expected == actual - -def test_resource_change_path(): - project = "scallop" - location = "abalone" - preview = "squid" - resource_change = "clam" - expected = "projects/{project}/locations/{location}/previews/{preview}/resourceChanges/{resource_change}".format(project=project, location=location, preview=preview, resource_change=resource_change, ) - actual = ConfigClient.resource_change_path(project, location, preview, resource_change) - assert expected == actual - - -def test_parse_resource_change_path(): - expected = { - "project": "whelk", - "location": "octopus", - "preview": "oyster", - "resource_change": "nudibranch", - } - path = ConfigClient.resource_change_path(**expected) - - # Check that the path construction is reversible. - actual = ConfigClient.parse_resource_change_path(path) - assert expected == actual - -def test_resource_drift_path(): - project = "cuttlefish" - location = "mussel" - preview = "winkle" - resource_drift = "nautilus" - expected = "projects/{project}/locations/{location}/previews/{preview}/resourceDrifts/{resource_drift}".format(project=project, location=location, preview=preview, resource_drift=resource_drift, ) - actual = ConfigClient.resource_drift_path(project, location, preview, resource_drift) - assert expected == actual - - -def test_parse_resource_drift_path(): - expected = { - "project": "scallop", - "location": "abalone", - "preview": "squid", - "resource_drift": "clam", - } - path = ConfigClient.resource_drift_path(**expected) - - # Check that the path construction is reversible. - actual = ConfigClient.parse_resource_drift_path(path) - assert expected == actual - -def test_revision_path(): - project = "whelk" - location = "octopus" - deployment = "oyster" - revision = "nudibranch" - expected = "projects/{project}/locations/{location}/deployments/{deployment}/revisions/{revision}".format(project=project, location=location, deployment=deployment, revision=revision, ) - actual = ConfigClient.revision_path(project, location, deployment, revision) - assert expected == actual - - -def test_parse_revision_path(): - expected = { - "project": "cuttlefish", - "location": "mussel", - "deployment": "winkle", - "revision": "nautilus", - } - path = ConfigClient.revision_path(**expected) - - # Check that the path construction is reversible. - actual = ConfigClient.parse_revision_path(path) - assert expected == actual - -def test_service_account_path(): - project = "scallop" - service_account = "abalone" - expected = "projects/{project}/serviceAccounts/{service_account}".format(project=project, service_account=service_account, ) - actual = ConfigClient.service_account_path(project, service_account) - assert expected == actual - - -def test_parse_service_account_path(): - expected = { - "project": "squid", - "service_account": "clam", - } - path = ConfigClient.service_account_path(**expected) - - # Check that the path construction is reversible. - actual = ConfigClient.parse_service_account_path(path) - assert expected == actual - -def test_terraform_version_path(): - project = "whelk" - location = "octopus" - terraform_version = "oyster" - expected = "projects/{project}/locations/{location}/terraformVersions/{terraform_version}".format(project=project, location=location, terraform_version=terraform_version, ) - actual = ConfigClient.terraform_version_path(project, location, terraform_version) - assert expected == actual - - -def test_parse_terraform_version_path(): - expected = { - "project": "nudibranch", - "location": "cuttlefish", - "terraform_version": "mussel", - } - path = ConfigClient.terraform_version_path(**expected) - - # Check that the path construction is reversible. - actual = ConfigClient.parse_terraform_version_path(path) - assert expected == actual - -def test_worker_pool_path(): - project = "winkle" - location = "nautilus" - worker_pool = "scallop" - expected = "projects/{project}/locations/{location}/workerPools/{worker_pool}".format(project=project, location=location, worker_pool=worker_pool, ) - actual = ConfigClient.worker_pool_path(project, location, worker_pool) - assert expected == actual - - -def test_parse_worker_pool_path(): - expected = { - "project": "abalone", - "location": "squid", - "worker_pool": "clam", - } - path = ConfigClient.worker_pool_path(**expected) - - # Check that the path construction is reversible. - actual = ConfigClient.parse_worker_pool_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "whelk" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = ConfigClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "octopus", - } - path = ConfigClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = ConfigClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "oyster" - expected = "folders/{folder}".format(folder=folder, ) - actual = ConfigClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nudibranch", - } - path = ConfigClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = ConfigClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "cuttlefish" - expected = "organizations/{organization}".format(organization=organization, ) - actual = ConfigClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "mussel", - } - path = ConfigClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = ConfigClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "winkle" - expected = "projects/{project}".format(project=project, ) - actual = ConfigClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nautilus", - } - path = ConfigClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = ConfigClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "scallop" - location = "abalone" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = ConfigClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "squid", - "location": "clam", - } - path = ConfigClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = ConfigClient.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.ConfigTransport, '_prep_wrapped_messages') as prep: - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.ConfigTransport, '_prep_wrapped_messages') as prep: - transport_class = ConfigClient.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 = ConfigClient( - 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 = ConfigAsyncClient( - 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 = ConfigClient( - 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 = ConfigAsyncClient( - 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 = ConfigClient( - 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 = ConfigAsyncClient( - 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_cancel_operation(transport: str = "grpc"): - client = ConfigClient( - 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 = ConfigAsyncClient( - 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 = ConfigClient( - 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 = ConfigAsyncClient( - 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 = ConfigClient( - 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 = ConfigAsyncClient( - 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_get_operation(transport: str = "grpc"): - client = ConfigClient( - 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 = ConfigAsyncClient( - 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 = ConfigClient( - 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 = ConfigAsyncClient( - 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 = ConfigClient( - 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 = ConfigAsyncClient( - 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_list_operations(transport: str = "grpc"): - client = ConfigClient( - 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 = ConfigAsyncClient( - 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 = ConfigClient( - 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 = ConfigAsyncClient( - 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 = ConfigClient( - 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 = ConfigAsyncClient( - 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_locations(transport: str = "grpc"): - client = ConfigClient( - 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 = ConfigAsyncClient( - 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 = ConfigClient( - 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 = ConfigAsyncClient( - 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 = ConfigClient( - 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 = ConfigAsyncClient( - 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_get_location(transport: str = "grpc"): - client = ConfigClient( - 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 = ConfigAsyncClient( - 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 = ConfigClient( - 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 = ConfigAsyncClient( - 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 = ConfigClient( - 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 = ConfigAsyncClient( - 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_set_iam_policy(transport: str = "grpc"): - client = ConfigClient( - 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 = ConfigAsyncClient( - 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 = ConfigClient( - 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 = ConfigAsyncClient( - 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 = ConfigClient( - 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 = ConfigAsyncClient( - 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_get_iam_policy(transport: str = "grpc"): - client = ConfigClient( - 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 = ConfigAsyncClient( - 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 = ConfigClient( - 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 = ConfigAsyncClient( - 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 = ConfigClient( - 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 = ConfigAsyncClient( - 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_test_iam_permissions(transport: str = "grpc"): - client = ConfigClient( - 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 = ConfigAsyncClient( - 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 = ConfigClient( - 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 = ConfigAsyncClient( - 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 = ConfigClient( - 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 = ConfigAsyncClient( - 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_transport_close_grpc(): - client = ConfigClient( - 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 = ConfigAsyncClient( - 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 = ConfigClient( - 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 = ConfigClient( - 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", [ - (ConfigClient, transports.ConfigGrpcTransport), - (ConfigAsyncClient, transports.ConfigGrpcAsyncIOTransport), -]) -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-config/google/cloud/config/__init__.py b/packages/google-cloud-config/google/cloud/config/__init__.py index 0c3495995bbb..f07c37a361c5 100644 --- a/packages/google-cloud-config/google/cloud/config/__init__.py +++ b/packages/google-cloud-config/google/cloud/config/__init__.py @@ -66,6 +66,7 @@ PreviewResult, PropertyChange, PropertyDrift, + ProviderConfig, QuotaValidation, Resource, ResourceCAIInfo, @@ -133,6 +134,7 @@ "PreviewResult", "PropertyChange", "PropertyDrift", + "ProviderConfig", "Resource", "ResourceCAIInfo", "ResourceChange", diff --git a/packages/google-cloud-config/google/cloud/config_v1/__init__.py b/packages/google-cloud-config/google/cloud/config_v1/__init__.py index d60af2bc0978..784e260f4877 100644 --- a/packages/google-cloud-config/google/cloud/config_v1/__init__.py +++ b/packages/google-cloud-config/google/cloud/config_v1/__init__.py @@ -65,6 +65,7 @@ PreviewResult, PropertyChange, PropertyDrift, + ProviderConfig, QuotaValidation, Resource, ResourceCAIInfo, @@ -132,6 +133,7 @@ "PreviewResult", "PropertyChange", "PropertyDrift", + "ProviderConfig", "QuotaValidation", "Resource", "ResourceCAIInfo", diff --git a/packages/google-cloud-config/google/cloud/config_v1/services/config/async_client.py b/packages/google-cloud-config/google/cloud/config_v1/services/config/async_client.py index 98607c67d0e7..9cf1d700785b 100644 --- a/packages/google-cloud-config/google/cloud/config_v1/services/config/async_client.py +++ b/packages/google-cloud-config/google/cloud/config_v1/services/config/async_client.py @@ -28,7 +28,6 @@ Type, Union, ) -import uuid from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 diff --git a/packages/google-cloud-config/google/cloud/config_v1/services/config/client.py b/packages/google-cloud-config/google/cloud/config_v1/services/config/client.py index d1562c2ecb41..d3daecf6e1d3 100644 --- a/packages/google-cloud-config/google/cloud/config_v1/services/config/client.py +++ b/packages/google-cloud-config/google/cloud/config_v1/services/config/client.py @@ -32,7 +32,6 @@ Union, cast, ) -import uuid import warnings from google.api_core import client_options as client_options_lib diff --git a/packages/google-cloud-config/google/cloud/config_v1/types/__init__.py b/packages/google-cloud-config/google/cloud/config_v1/types/__init__.py index 786b2586d664..f672a503cc09 100644 --- a/packages/google-cloud-config/google/cloud/config_v1/types/__init__.py +++ b/packages/google-cloud-config/google/cloud/config_v1/types/__init__.py @@ -59,6 +59,7 @@ PreviewResult, PropertyChange, PropertyDrift, + ProviderConfig, QuotaValidation, Resource, ResourceCAIInfo, @@ -124,6 +125,7 @@ "PreviewResult", "PropertyChange", "PropertyDrift", + "ProviderConfig", "Resource", "ResourceCAIInfo", "ResourceChange", diff --git a/packages/google-cloud-config/google/cloud/config_v1/types/config.py b/packages/google-cloud-config/google/cloud/config_v1/types/config.py index 63e89aec72ac..fc9a71020e51 100644 --- a/packages/google-cloud-config/google/cloud/config_v1/types/config.py +++ b/packages/google-cloud-config/google/cloud/config_v1/types/config.py @@ -88,6 +88,7 @@ "ListResourceDriftsRequest", "ListResourceDriftsResponse", "GetResourceDriftRequest", + "ProviderConfig", }, ) @@ -238,6 +239,9 @@ class Deployment(proto.Message): deployments during automation. See https://google.aip.dev/148#annotations for details on format and size limitations. + provider_config (google.cloud.config_v1.types.ProviderConfig): + Optional. This field specifies the provider + configurations. """ class State(proto.Enum): @@ -443,6 +447,11 @@ class LockState(proto.Enum): proto.STRING, number=24, ) + provider_config: "ProviderConfig" = proto.Field( + proto.MESSAGE, + number=25, + message="ProviderConfig", + ) class TerraformBlueprint(proto.Message): @@ -1161,6 +1170,9 @@ class Revision(proto.Message): resources in terraform configuration files. There are limited resources on which quota validation applies. + provider_config (google.cloud.config_v1.types.ProviderConfig): + Output only. This field specifies the + provider configurations. """ class Action(proto.Enum): @@ -1319,6 +1331,11 @@ class ErrorCode(proto.Enum): number=20, enum="QuotaValidation", ) + provider_config: "ProviderConfig" = proto.Field( + proto.MESSAGE, + number=21, + message="ProviderConfig", + ) class TerraformError(proto.Message): @@ -2054,6 +2071,9 @@ class Preview(proto.Message): preview during automation. See https://google.aip.dev/148#annotations for details on format and size limitations. + provider_config (google.cloud.config_v1.types.ProviderConfig): + Optional. This field specifies the provider + configurations. """ class State(proto.Enum): @@ -2237,6 +2257,11 @@ class ErrorCode(proto.Enum): proto.STRING, number=20, ) + provider_config: "ProviderConfig" = proto.Field( + proto.MESSAGE, + number=21, + message="ProviderConfig", + ) class PreviewOperationMetadata(proto.Message): @@ -3255,4 +3280,38 @@ class GetResourceDriftRequest(proto.Message): ) +class ProviderConfig(proto.Message): + r"""ProviderConfig contains the provider configurations. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + source_type (google.cloud.config_v1.types.ProviderConfig.ProviderSource): + Optional. ProviderSource specifies the source + type of the provider. + + This field is a member of `oneof`_ ``_source_type``. + """ + + class ProviderSource(proto.Enum): + r"""ProviderSource represents the source type of the provider. + + Values: + PROVIDER_SOURCE_UNSPECIFIED (0): + Unspecified source type, default to public + sources. + SERVICE_MAINTAINED (1): + Service maintained provider source type. + """ + PROVIDER_SOURCE_UNSPECIFIED = 0 + SERVICE_MAINTAINED = 1 + + source_type: ProviderSource = proto.Field( + proto.ENUM, + number=1, + optional=True, + enum=ProviderSource, + ) + + __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-config/tests/unit/gapic/config_v1/test_config.py b/packages/google-cloud-config/tests/unit/gapic/config_v1/test_config.py index 325a6055e8ae..7bc525bc0701 100644 --- a/packages/google-cloud-config/tests/unit/gapic/config_v1/test_config.py +++ b/packages/google-cloud-config/tests/unit/gapic/config_v1/test_config.py @@ -14,7 +14,6 @@ # limitations under the License. # import os -import re # try/except added for compatibility with python < 3.8 try: @@ -18835,6 +18834,7 @@ def test_create_deployment_rest_call_success(request_type): "tf_version": "tf_version_value", "quota_validation": 1, "annotations": {}, + "provider_config": {"source_type": 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 @@ -19078,6 +19078,7 @@ def test_update_deployment_rest_call_success(request_type): "tf_version": "tf_version_value", "quota_validation": 1, "annotations": {}, + "provider_config": {"source_type": 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 @@ -20812,6 +20813,7 @@ def test_create_preview_rest_call_success(request_type): "tf_version": "tf_version_value", "tf_version_constraint": "tf_version_constraint_value", "annotations": {}, + "provider_config": {"source_type": 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