From f282357baedfedb99e852b3969781e4c85278b7a Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Sat, 13 Jan 2024 01:22:40 +0000 Subject: [PATCH 1/2] feat: added Terraform Plan PiperOrigin-RevId: 597969500 Source-Link: https://github.com/googleapis/googleapis/commit/ea0432d67aa7bde859a0bff438d099c78f89aaa0 Source-Link: https://github.com/googleapis/googleapis-gen/commit/970abcc20508523bb4de6e6c77e6c658f893400b Copy-Tag: eyJwIjoicGFja2FnZXMvZ29vZ2xlLWNsb3VkLWNvbmZpZy8uT3dsQm90LnlhbWwiLCJoIjoiOTcwYWJjYzIwNTA4NTIzYmI0ZGU2ZTZjNzdlNmM2NThmODkzNDAwYiJ9 --- .../google-cloud-config/v1/.coveragerc | 13 + .../google-cloud-config/v1/.flake8 | 33 + .../google-cloud-config/v1/MANIFEST.in | 2 + .../google-cloud-config/v1/README.rst | 49 + .../v1/docs/_static/custom.css | 3 + .../google-cloud-config/v1/docs/conf.py | 376 + .../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 | 7 + .../v1/google/cloud/config/__init__.py | 117 + .../v1/google/cloud/config/gapic_version.py | 16 + .../v1/google/cloud/config/py.typed | 2 + .../v1/google/cloud/config_v1/__init__.py | 118 + .../cloud/config_v1/gapic_metadata.json | 343 + .../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 | 3119 ++++ .../cloud/config_v1/services/config/client.py | 3366 ++++ .../cloud/config_v1/services/config/pagers.py | 502 + .../services/config/transports/__init__.py | 38 + .../services/config/transports/base.py | 521 + .../services/config/transports/grpc.py | 1005 ++ .../config/transports/grpc_asyncio.py | 1004 ++ .../services/config/transports/rest.py | 3431 ++++ .../google/cloud/config_v1/types/__init__.py | 110 + .../v1/google/cloud/config_v1/types/config.py | 2442 +++ .../google-cloud-config/v1/mypy.ini | 3 + .../google-cloud-config/v1/noxfile.py | 177 + ...enerated_config_create_deployment_async.py | 61 + ...generated_config_create_deployment_sync.py | 61 + ...1_generated_config_create_preview_async.py | 60 + ...v1_generated_config_create_preview_sync.py | 60 + ...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 + ...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 + ...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 + ...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 + ..._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 | 3414 ++++ .../v1/scripts/fixup_config_v1_keywords.py | 196 + .../google-cloud-config/v1/setup.py | 91 + .../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.7.txt | 10 + .../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 | 14019 ++++++++++++++++ 87 files changed, 36977 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/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/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/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/__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/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_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_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_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_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.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..29227d4cf419 --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/.flake8 @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Generated by synthtool. DO NOT EDIT! +[flake8] +ignore = E203, E266, E501, W503 +exclude = + # Exclude generated code. + **/proto/** + **/gapic/** + **/services/** + **/types/** + *_pb2.py + + # Standard linting exemptions. + **/.nox/** + __pycache__, + .git, + *.pyc, + conf.py 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..7aa890629865 --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/config *.py +recursive-include google/cloud/config_v1 *.py 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..9b1293c47a76 --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/README.rst @@ -0,0 +1,49 @@ +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 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..06423be0b592 --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/docs/_static/custom.css @@ -0,0 +1,3 @@ +dl.field-list > dt { + min-width: 100px +} 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..9da1ab185d60 --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/docs/conf.py @@ -0,0 +1,376 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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("..")) + +__version__ = "0.1.0" + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +needs_sphinx = "4.0.1" + +# 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.napoleon", + "sphinx.ext.todo", + "sphinx.ext.viewcode", +] + +# autodoc/autosummary flags +autoclass_content = "both" +autodoc_default_flags = ["members"] +autosummary_generate = True + + +# Add any paths that contain templates here, relative to this directory. +templates_path = ["_templates"] + +# Allow markdown includes (so releases.md can include CHANGLEOG.md) +# http://www.sphinx-doc.org/en/master/markdown.html +source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +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"2023, Google, LLC" +author = u"Google APIs" # TODO: autogenerate this bit + +# 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 = 'en' + +# 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"] + +# 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 Python", + "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", + u"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", + u"google-cloud-config Documentation", + author, + "google-cloud-config", + "GAPIC library for Google Cloud Config API", + "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": ("http://python.readthedocs.org/en/latest/", None), + "gax": ("https://gax-python.readthedocs.org/en/latest/", None), + "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), + "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), + "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), + "grpc": ("https://grpc.io/grpc/python/", None), + "requests": ("http://requests.kennethreitz.org/en/stable/", None), + "proto": ("https://proto-plus-python.readthedocs.io/en/stable", 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..91d7ab9a2e0c --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + config_v1/services + config_v1/types 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..cebce4ca0bd1 --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/google/cloud/config/__init__.py @@ -0,0 +1,117 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 GetResourceRequest +from google.cloud.config_v1.types.config import GetRevisionRequest +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 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 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 Resource +from google.cloud.config_v1.types.config import ResourceCAIInfo +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 UnlockDeploymentRequest +from google.cloud.config_v1.types.config import UpdateDeploymentRequest + +__all__ = ('ConfigClient', + 'ConfigAsyncClient', + 'ApplyResults', + 'CreateDeploymentRequest', + 'CreatePreviewRequest', + 'DeleteDeploymentRequest', + 'DeletePreviewRequest', + 'DeleteStatefileRequest', + 'Deployment', + 'DeploymentOperationMetadata', + 'ExportDeploymentStatefileRequest', + 'ExportLockInfoRequest', + 'ExportPreviewResultRequest', + 'ExportPreviewResultResponse', + 'ExportRevisionStatefileRequest', + 'GetDeploymentRequest', + 'GetPreviewRequest', + 'GetResourceRequest', + 'GetRevisionRequest', + 'GitSource', + 'ImportStatefileRequest', + 'ListDeploymentsRequest', + 'ListDeploymentsResponse', + 'ListPreviewsRequest', + 'ListPreviewsResponse', + 'ListResourcesRequest', + 'ListResourcesResponse', + 'ListRevisionsRequest', + 'ListRevisionsResponse', + 'LockDeploymentRequest', + 'LockInfo', + 'OperationMetadata', + 'Preview', + 'PreviewArtifacts', + 'PreviewOperationMetadata', + 'PreviewResult', + 'Resource', + 'ResourceCAIInfo', + 'ResourceTerraformInfo', + 'Revision', + 'Statefile', + 'TerraformBlueprint', + 'TerraformError', + 'TerraformOutput', + 'TerraformVariable', + 'UnlockDeploymentRequest', + 'UpdateDeploymentRequest', +) 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..360a0d13ebdd --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/google/cloud/config/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..cd5c1e43912e --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/__init__.py @@ -0,0 +1,118 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 GetResourceRequest +from .types.config import GetRevisionRequest +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 ListResourcesRequest +from .types.config import ListResourcesResponse +from .types.config import ListRevisionsRequest +from .types.config import ListRevisionsResponse +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 Resource +from .types.config import ResourceCAIInfo +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 UnlockDeploymentRequest +from .types.config import UpdateDeploymentRequest + +__all__ = ( + 'ConfigAsyncClient', +'ApplyResults', +'ConfigClient', +'CreateDeploymentRequest', +'CreatePreviewRequest', +'DeleteDeploymentRequest', +'DeletePreviewRequest', +'DeleteStatefileRequest', +'Deployment', +'DeploymentOperationMetadata', +'ExportDeploymentStatefileRequest', +'ExportLockInfoRequest', +'ExportPreviewResultRequest', +'ExportPreviewResultResponse', +'ExportRevisionStatefileRequest', +'GetDeploymentRequest', +'GetPreviewRequest', +'GetResourceRequest', +'GetRevisionRequest', +'GitSource', +'ImportStatefileRequest', +'ListDeploymentsRequest', +'ListDeploymentsResponse', +'ListPreviewsRequest', +'ListPreviewsResponse', +'ListResourcesRequest', +'ListResourcesResponse', +'ListRevisionsRequest', +'ListRevisionsResponse', +'LockDeploymentRequest', +'LockInfo', +'OperationMetadata', +'Preview', +'PreviewArtifacts', +'PreviewOperationMetadata', +'PreviewResult', +'Resource', +'ResourceCAIInfo', +'ResourceTerraformInfo', +'Revision', +'Statefile', +'TerraformBlueprint', +'TerraformError', +'TerraformOutput', +'TerraformVariable', +'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..190bb0825b1c --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/gapic_metadata.json @@ -0,0 +1,343 @@ + { + "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" + ] + }, + "GetRevision": { + "methods": [ + "get_revision" + ] + }, + "ImportStatefile": { + "methods": [ + "import_statefile" + ] + }, + "ListDeployments": { + "methods": [ + "list_deployments" + ] + }, + "ListPreviews": { + "methods": [ + "list_previews" + ] + }, + "ListResources": { + "methods": [ + "list_resources" + ] + }, + "ListRevisions": { + "methods": [ + "list_revisions" + ] + }, + "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" + ] + }, + "GetRevision": { + "methods": [ + "get_revision" + ] + }, + "ImportStatefile": { + "methods": [ + "import_statefile" + ] + }, + "ListDeployments": { + "methods": [ + "list_deployments" + ] + }, + "ListPreviews": { + "methods": [ + "list_previews" + ] + }, + "ListResources": { + "methods": [ + "list_resources" + ] + }, + "ListRevisions": { + "methods": [ + "list_revisions" + ] + }, + "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" + ] + }, + "GetRevision": { + "methods": [ + "get_revision" + ] + }, + "ImportStatefile": { + "methods": [ + "import_statefile" + ] + }, + "ListDeployments": { + "methods": [ + "list_deployments" + ] + }, + "ListPreviews": { + "methods": [ + "list_previews" + ] + }, + "ListResources": { + "methods": [ + "list_resources" + ] + }, + "ListRevisions": { + "methods": [ + "list_revisions" + ] + }, + "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..360a0d13ebdd --- /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 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..89a37dc92c5a --- /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 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..a4e7fa857980 --- /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 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..233fc14ac689 --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/async_client.py @@ -0,0 +1,3119 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 +import functools +import re +from typing import Dict, 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 + +try: + OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.AsyncRetry, object] # 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 + + +class ConfigAsyncClient: + """Infrastructure Manager is a managed service that automates + the deployment and management of Google Cloud infrastructure + resources. + """ + + _client: ConfigClient + + DEFAULT_ENDPOINT = ConfigClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = ConfigClient.DEFAULT_MTLS_ENDPOINT + + 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) + 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) + 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 + + get_transport_class = functools.partial(type(ConfigClient).get_transport_class, type(ConfigClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, ConfigTransport] = "grpc_asyncio", + client_options: Optional[ClientOptions] = 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 (Union[str, ~.ConfigTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "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). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS 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. + + 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, + + ) + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + 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 = gapic_v1.method_async.wrap_method( + self._client._transport.list_deployments, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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), + )), + ) + + # 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, + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + 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 = gapic_v1.method_async.wrap_method( + self._client._transport.get_deployment, + default_timeout=None, + client_info=DEFAULT_CLIENT_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), + )), + ) + + # 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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. + has_flattened_params = any([parent, deployment, deployment_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + 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 = gapic_v1.method_async.wrap_method( + self._client._transport.create_deployment, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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), + )), + ) + + # 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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. + has_flattened_params = any([deployment, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + 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 = gapic_v1.method_async.wrap_method( + self._client._transport.update_deployment, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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), + )), + ) + + # 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + 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 = gapic_v1.method_async.wrap_method( + self._client._transport.delete_deployment, + default_timeout=None, + client_info=DEFAULT_CLIENT_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), + )), + ) + + # 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + 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 = gapic_v1.method_async.wrap_method( + self._client._transport.list_revisions, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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), + )), + ) + + # 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, + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + 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 = gapic_v1.method_async.wrap_method( + self._client._transport.get_revision, + default_timeout=None, + client_info=DEFAULT_CLIENT_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), + )), + ) + + # 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + 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 = gapic_v1.method_async.wrap_method( + self._client._transport.get_resource, + default_timeout=None, + client_info=DEFAULT_CLIENT_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), + )), + ) + + # 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, str]] = (), + ) -> pagers.ListResourcesAsyncPager: + r"""Lists [Resource][google.cloud.config.v1.Resource]s 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, str]]): Strings which should be + sent along with the request as metadata. + + 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. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + 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 = gapic_v1.method_async.wrap_method( + self._client._transport.list_resources, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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), + )), + ) + + # 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, + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.config_v1.types.Statefile: + Contains info about a Terraform state + file + + """ + # Create or coerce a protobuf request object. + request = config.ExportDeploymentStatefileRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.export_deployment_statefile, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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), + )), + ) + + # 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.config_v1.types.Statefile: + Contains info about a Terraform state + file + + """ + # Create or coerce a protobuf request object. + request = config.ExportRevisionStatefileRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.export_revision_statefile, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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), + )), + ) + + # 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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. + has_flattened_params = any([parent, lock_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + 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 = gapic_v1.method_async.wrap_method( + self._client._transport.import_statefile, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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), + )), + ) + + # 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + 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 = gapic_v1.method_async.wrap_method( + self._client._transport.delete_statefile, + default_timeout=None, + client_info=DEFAULT_CLIENT_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), + )), + ) + + # 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + 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 = gapic_v1.method_async.wrap_method( + self._client._transport.lock_deployment, + default_timeout=None, + client_info=DEFAULT_CLIENT_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), + )), + ) + + # 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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. + has_flattened_params = any([name, lock_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + 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 = gapic_v1.method_async.wrap_method( + self._client._transport.unlock_deployment, + default_timeout=None, + client_info=DEFAULT_CLIENT_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), + )), + ) + + # 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + 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 = gapic_v1.method_async.wrap_method( + self._client._transport.export_lock_info, + default_timeout=None, + client_info=DEFAULT_CLIENT_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), + )), + ) + + # 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, str]] = (), + ) -> 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" + + 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, str]]): Strings which should be + sent along with the request as metadata. + + 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. + has_flattened_params = any([parent, preview]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + 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 = gapic_v1.method_async.wrap_method( + self._client._transport.create_preview, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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), + )), + ) + + # 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + 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 = gapic_v1.method_async.wrap_method( + self._client._transport.get_preview, + default_timeout=None, + client_info=DEFAULT_CLIENT_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), + )), + ) + + # 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + 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 = gapic_v1.method_async.wrap_method( + self._client._transport.list_previews, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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), + )), + ) + + # 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, + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + 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 = gapic_v1.method_async.wrap_method( + self._client._transport.delete_preview, + default_timeout=None, + client_info=DEFAULT_CLIENT_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), + )), + ) + + # 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.config_v1.types.ExportPreviewResultResponse: + A response to ExportPreviewResult call. Contains preview + results. + + """ + # Create or coerce a protobuf request object. + request = config.ExportPreviewResultRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.export_preview_result, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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), + )), + ) + + # 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + 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 = gapic_v1.method_async.wrap_method( + self._client._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_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),)), + ) + + # 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + 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 = gapic_v1.method_async.wrap_method( + self._client._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_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),)), + ) + + # 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + 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 = gapic_v1.method_async.wrap_method( + self._client._transport.delete_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_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),)), + ) + + # 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + 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 = gapic_v1.method_async.wrap_method( + self._client._transport.cancel_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_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),)), + ) + + # 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + 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 = gapic_v1.method_async.wrap_method( + self._client._transport.set_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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),)), + ) + + # 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + 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 = gapic_v1.method_async.wrap_method( + self._client._transport.get_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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),)), + ) + + # 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + 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 = gapic_v1.method_async.wrap_method( + self._client._transport.test_iam_permissions, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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),)), + ) + + # 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + 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 = gapic_v1.method_async.wrap_method( + self._client._transport.get_location, + default_timeout=None, + client_info=DEFAULT_CLIENT_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),)), + ) + + # 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + 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 = gapic_v1.method_async.wrap_method( + self._client._transport.list_locations, + default_timeout=None, + client_info=DEFAULT_CLIENT_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),)), + ) + + # 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__) + + +__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..807add264d43 --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/client.py @@ -0,0 +1,3366 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 +import os +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast + +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 + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # 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 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") + + DEFAULT_ENDPOINT = "config.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @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 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 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): + """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. + """ + 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 + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, 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 (Union[str, ConfigTransport]): The + transport to use. 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. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "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). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS 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. + 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. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + client_options = cast(client_options_lib.ClientOptions, client_options) + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(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. + if isinstance(transport, ConfigTransport): + # transport is a ConfigTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + 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 = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a config.ListDeploymentsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + 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), + )), + ) + + # 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, + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a config.GetDeploymentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + 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), + )), + ) + + # 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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. + has_flattened_params = any([parent, deployment, deployment_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a config.CreateDeploymentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + 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), + )), + ) + + # 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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. + has_flattened_params = any([deployment, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a config.UpdateDeploymentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + 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), + )), + ) + + # 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a config.DeleteDeploymentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + 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), + )), + ) + + # 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a config.ListRevisionsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + 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), + )), + ) + + # 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, + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a config.GetRevisionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + 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), + )), + ) + + # 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a config.GetResourceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + 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), + )), + ) + + # 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, str]] = (), + ) -> pagers.ListResourcesPager: + r"""Lists [Resource][google.cloud.config.v1.Resource]s 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, str]]): Strings which should be + sent along with the request as metadata. + + 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. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a config.ListResourcesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + 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), + )), + ) + + # 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, + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.config_v1.types.Statefile: + Contains info about a Terraform state + file + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a config.ExportDeploymentStatefileRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + 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), + )), + ) + + # 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.config_v1.types.Statefile: + Contains info about a Terraform state + file + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a config.ExportRevisionStatefileRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + 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), + )), + ) + + # 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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. + has_flattened_params = any([parent, lock_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a config.ImportStatefileRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + 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), + )), + ) + + # 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a config.DeleteStatefileRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + 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), + )), + ) + + # 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a config.LockDeploymentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + 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), + )), + ) + + # 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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. + has_flattened_params = any([name, lock_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a config.UnlockDeploymentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + 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), + )), + ) + + # 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a config.ExportLockInfoRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + 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), + )), + ) + + # 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, str]] = (), + ) -> 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" + + 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, str]]): Strings which should be + sent along with the request as metadata. + + 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. + has_flattened_params = any([parent, preview]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a config.CreatePreviewRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + 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), + )), + ) + + # 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a config.GetPreviewRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + 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), + )), + ) + + # 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a config.ListPreviewsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + 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), + )), + ) + + # 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, + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a config.DeletePreviewRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + 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), + )), + ) + + # 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.config_v1.types.ExportPreviewResultResponse: + A response to ExportPreviewResult call. Contains preview + results. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a config.ExportPreviewResultRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + 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), + )), + ) + + # 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + 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 = gapic_v1.method.wrap_method( + self._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_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),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + 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 = gapic_v1.method.wrap_method( + self._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_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),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + 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 = gapic_v1.method.wrap_method( + self._transport.delete_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_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),)), + ) + + # 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + 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 = gapic_v1.method.wrap_method( + self._transport.cancel_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_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),)), + ) + + # 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + 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 = gapic_v1.method.wrap_method( + self._transport.set_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + 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 = gapic_v1.method.wrap_method( + self._transport.get_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def test_iam_permissions( + self, + request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + 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 = gapic_v1.method.wrap_method( + self._transport.test_iam_permissions, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + 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 = gapic_v1.method.wrap_method( + self._transport.get_location, + default_timeout=None, + client_info=DEFAULT_CLIENT_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),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + 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 = gapic_v1.method.wrap_method( + self._transport.list_locations, + default_timeout=None, + client_info=DEFAULT_CLIENT_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),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__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..817c71ba5592 --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/pagers.py @@ -0,0 +1,502 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +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, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """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. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = config.ListDeploymentsRequest(request) + self._response = response + 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, 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, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """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. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = config.ListDeploymentsRequest(request) + self._response = response + 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, 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, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """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. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = config.ListRevisionsRequest(request) + self._response = response + 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, 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, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """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. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = config.ListRevisionsRequest(request) + self._response = response + 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, 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, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """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. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = config.ListResourcesRequest(request) + self._response = response + 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, 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, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """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. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = config.ListResourcesRequest(request) + self._response = response + 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, 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, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """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. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = config.ListPreviewsRequest(request) + self._response = response + 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, 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, + *, + metadata: Sequence[Tuple[str, str]] = ()): + """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. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = config.ListPreviewsRequest(request) + self._response = response + 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, 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) 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..30139049a722 --- /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 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..13f602b43833 --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/transports/base.py @@ -0,0 +1,521 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 + +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__) + + +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. + 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 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: + 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 + + 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, + ), + } + + 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_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..93dcf49a8429 --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/transports/grpc.py @@ -0,0 +1,1005 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 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 + +import grpc # 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 + + +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[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. + 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 ``channel`` 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 ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + 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 ``channel`` 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 ``channel`` 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 channel: + # Ignore credentials if a channel was passed. + credentials = False + # 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: + self._grpc_channel = type(self).create_channel( + 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), + ], + ) + + # Wrap messages. This must be done after self._grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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 [Resource][google.cloud.config.v1.Resource]s 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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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'] + + def close(self): + self.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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..946d198514de --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/transports/grpc_asyncio.py @@ -0,0 +1,1004 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 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 operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # 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 + + +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`. + This argument is ignored if ``channel`` 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`. + 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[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. + 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 ``channel`` 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 ``channel`` 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[aio.Channel]): A ``Channel`` instance through + which to make calls. + 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 ``channel`` 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 ``channel`` 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 channel: + # Ignore credentials if a channel was passed. + credentials = False + # 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: + self._grpc_channel = type(self).create_channel( + 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), + ], + ) + + # Wrap messages. This must be done after self._grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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 [Resource][google.cloud.config.v1.Resource]s 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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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'] + + def close(self): + return self.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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..a1a4f1801c92 --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/transports/rest.py @@ -0,0 +1,3431 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.auth.transport.requests import AuthorizedSession # type: ignore +import json # type: ignore +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # 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 path_template +from google.api_core import gapic_v1 + +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 +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +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 .base import ConfigTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_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_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_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_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_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, str]]) -> Tuple[config.CreateDeploymentRequest, Sequence[Tuple[str, str]]]: + """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 + + 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_create_preview(self, request: config.CreatePreviewRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[config.CreatePreviewRequest, Sequence[Tuple[str, str]]]: + """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 + + 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_deployment(self, request: config.DeleteDeploymentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[config.DeleteDeploymentRequest, Sequence[Tuple[str, str]]]: + """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 + + 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_preview(self, request: config.DeletePreviewRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[config.DeletePreviewRequest, Sequence[Tuple[str, str]]]: + """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 + + 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_statefile(self, request: config.DeleteStatefileRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[config.DeleteStatefileRequest, Sequence[Tuple[str, str]]]: + """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, str]]) -> Tuple[config.ExportDeploymentStatefileRequest, Sequence[Tuple[str, str]]]: + """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 + + 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_export_lock_info(self, request: config.ExportLockInfoRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[config.ExportLockInfoRequest, Sequence[Tuple[str, str]]]: + """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 + + 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_export_preview_result(self, request: config.ExportPreviewResultRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[config.ExportPreviewResultRequest, Sequence[Tuple[str, str]]]: + """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 + + 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_export_revision_statefile(self, request: config.ExportRevisionStatefileRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[config.ExportRevisionStatefileRequest, Sequence[Tuple[str, str]]]: + """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 + + 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_deployment(self, request: config.GetDeploymentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[config.GetDeploymentRequest, Sequence[Tuple[str, str]]]: + """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 + + 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_preview(self, request: config.GetPreviewRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[config.GetPreviewRequest, Sequence[Tuple[str, str]]]: + """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 + + 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_resource(self, request: config.GetResourceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[config.GetResourceRequest, Sequence[Tuple[str, str]]]: + """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 + + 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_revision(self, request: config.GetRevisionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[config.GetRevisionRequest, Sequence[Tuple[str, str]]]: + """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 + + 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_import_statefile(self, request: config.ImportStatefileRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[config.ImportStatefileRequest, Sequence[Tuple[str, str]]]: + """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 + + 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_deployments(self, request: config.ListDeploymentsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[config.ListDeploymentsRequest, Sequence[Tuple[str, str]]]: + """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 + + 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_previews(self, request: config.ListPreviewsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[config.ListPreviewsRequest, Sequence[Tuple[str, str]]]: + """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 + + 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_resources(self, request: config.ListResourcesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[config.ListResourcesRequest, Sequence[Tuple[str, str]]]: + """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 + + 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_revisions(self, request: config.ListRevisionsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[config.ListRevisionsRequest, Sequence[Tuple[str, str]]]: + """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 + + 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_lock_deployment(self, request: config.LockDeploymentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[config.LockDeploymentRequest, Sequence[Tuple[str, str]]]: + """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 + + 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_unlock_deployment(self, request: config.UnlockDeploymentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[config.UnlockDeploymentRequest, Sequence[Tuple[str, str]]]: + """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 + + 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_update_deployment(self, request: config.UpdateDeploymentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[config.UpdateDeploymentRequest, Sequence[Tuple[str, str]]]: + """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 + + 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_location( + self, request: locations_pb2.GetLocationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[locations_pb2.GetLocationRequest, Sequence[Tuple[str, str]]]: + """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, str]] + ) -> Tuple[locations_pb2.ListLocationsRequest, Sequence[Tuple[str, str]]]: + """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, str]] + ) -> Tuple[iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, str]]]: + """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, str]] + ) -> Tuple[iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, str]]]: + """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, str]] + ) -> Tuple[iam_policy_pb2.TestIamPermissionsRequest, Sequence[Tuple[str, str]]]: + """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, str]] + ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, str]]]: + """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, str]] + ) -> Tuple[operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, str]]]: + """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, str]] + ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: + """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, str]] + ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: + """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(ConfigTransport): + """REST 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 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. + 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 + 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 + ) + 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(ConfigRestStub): + def __hash__(self): + return hash("CreateDeployment") + + __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} + + def __call__(self, + request: config.CreateDeploymentRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*}/deployments', + 'body': 'deployment', + }, + ] + request, metadata = self._interceptor.pre_create_deployment(request, metadata) + pb_request = config.CreateDeploymentRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=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) + return resp + + class _CreatePreview(ConfigRestStub): + def __hash__(self): + return hash("CreatePreview") + + __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} + + def __call__(self, + request: config.CreatePreviewRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*}/previews', + 'body': 'preview', + }, + ] + request, metadata = self._interceptor.pre_create_preview(request, metadata) + pb_request = config.CreatePreviewRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=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) + return resp + + class _DeleteDeployment(ConfigRestStub): + def __hash__(self): + return hash("DeleteDeployment") + + __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} + + def __call__(self, + request: config.DeleteDeploymentRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/deployments/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_deployment(request, metadata) + pb_request = config.DeleteDeploymentRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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) + return resp + + class _DeletePreview(ConfigRestStub): + def __hash__(self): + return hash("DeletePreview") + + __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} + + def __call__(self, + request: config.DeletePreviewRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/previews/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_preview(request, metadata) + pb_request = config.DeletePreviewRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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) + return resp + + class _DeleteStatefile(ConfigRestStub): + def __hash__(self): + return hash("DeleteStatefile") + + __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} + + def __call__(self, + request: config.DeleteStatefileRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + 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, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{name=projects/*/locations/*/deployments/*}:deleteState', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_delete_statefile(request, metadata) + pb_request = config.DeleteStatefileRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=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(ConfigRestStub): + def __hash__(self): + return hash("ExportDeploymentStatefile") + + __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} + + def __call__(self, + request: config.ExportDeploymentStatefileRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.config.Statefile: + Contains info about a Terraform state + file + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*/deployments/*}:exportState', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_export_deployment_statefile(request, metadata) + pb_request = config.ExportDeploymentStatefileRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=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) + return resp + + class _ExportLockInfo(ConfigRestStub): + def __hash__(self): + return hash("ExportLockInfo") + + __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} + + def __call__(self, + request: config.ExportLockInfoRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.config.LockInfo: + Details about the lock which locked + the deployment. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/deployments/*}:exportLock', + }, + ] + request, metadata = self._interceptor.pre_export_lock_info(request, metadata) + pb_request = config.ExportLockInfoRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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) + return resp + + class _ExportPreviewResult(ConfigRestStub): + def __hash__(self): + return hash("ExportPreviewResult") + + __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} + + def __call__(self, + request: config.ExportPreviewResultRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.config.ExportPreviewResultResponse: + A response to ``ExportPreviewResult`` call. Contains + preview results. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*/previews/*}:export', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_export_preview_result(request, metadata) + pb_request = config.ExportPreviewResultRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=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) + return resp + + class _ExportRevisionStatefile(ConfigRestStub): + def __hash__(self): + return hash("ExportRevisionStatefile") + + __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} + + def __call__(self, + request: config.ExportRevisionStatefileRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.config.Statefile: + Contains info about a Terraform state + file + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*/deployments/*/revisions/*}:exportState', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_export_revision_statefile(request, metadata) + pb_request = config.ExportRevisionStatefileRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=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) + return resp + + class _GetDeployment(ConfigRestStub): + def __hash__(self): + return hash("GetDeployment") + + __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} + + def __call__(self, + request: config.GetDeploymentRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.config.Deployment: + A Deployment is a group of resources + and configs managed and provisioned by + Infra Manager. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/deployments/*}', + }, + ] + request, metadata = self._interceptor.pre_get_deployment(request, metadata) + pb_request = config.GetDeploymentRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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) + return resp + + class _GetPreview(ConfigRestStub): + def __hash__(self): + return hash("GetPreview") + + __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} + + def __call__(self, + request: config.GetPreviewRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/previews/*}', + }, + ] + request, metadata = self._interceptor.pre_get_preview(request, metadata) + pb_request = config.GetPreviewRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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) + return resp + + class _GetResource(ConfigRestStub): + def __hash__(self): + return hash("GetResource") + + __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} + + def __call__(self, + request: config.GetResourceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.config.Resource: + Resource represents a Google Cloud + Platform resource actuated by IM. + Resources are child resources of + Revisions. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/deployments/*/revisions/*/resources/*}', + }, + ] + request, metadata = self._interceptor.pre_get_resource(request, metadata) + pb_request = config.GetResourceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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) + return resp + + class _GetRevision(ConfigRestStub): + def __hash__(self): + return hash("GetRevision") + + __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} + + def __call__(self, + request: config.GetRevisionRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/deployments/*/revisions/*}', + }, + ] + request, metadata = self._interceptor.pre_get_revision(request, metadata) + pb_request = config.GetRevisionRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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) + return resp + + class _ImportStatefile(ConfigRestStub): + def __hash__(self): + return hash("ImportStatefile") + + __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} + + def __call__(self, + request: config.ImportStatefileRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.config.Statefile: + Contains info about a Terraform state + file + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*/deployments/*}:importState', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_import_statefile(request, metadata) + pb_request = config.ImportStatefileRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=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) + return resp + + class _ListDeployments(ConfigRestStub): + def __hash__(self): + return hash("ListDeployments") + + __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} + + def __call__(self, + request: config.ListDeploymentsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.config.ListDeploymentsResponse: + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*}/deployments', + }, + ] + request, metadata = self._interceptor.pre_list_deployments(request, metadata) + pb_request = config.ListDeploymentsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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) + return resp + + class _ListPreviews(ConfigRestStub): + def __hash__(self): + return hash("ListPreviews") + + __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} + + def __call__(self, + request: config.ListPreviewsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.config.ListPreviewsResponse: + A response to a ``ListPreviews`` call. Contains a list + of Previews. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*}/previews', + }, + ] + request, metadata = self._interceptor.pre_list_previews(request, metadata) + pb_request = config.ListPreviewsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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) + return resp + + class _ListResources(ConfigRestStub): + def __hash__(self): + return hash("ListResources") + + __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} + + def __call__(self, + request: config.ListResourcesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.config.ListResourcesResponse: + A response to a 'ListResources' call. + Contains a list of Resources. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*/deployments/*/revisions/*}/resources', + }, + ] + request, metadata = self._interceptor.pre_list_resources(request, metadata) + pb_request = config.ListResourcesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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) + return resp + + class _ListRevisions(ConfigRestStub): + def __hash__(self): + return hash("ListRevisions") + + __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} + + def __call__(self, + request: config.ListRevisionsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.config.ListRevisionsResponse: + A response to a 'ListRevisions' call. + Contains a list of Revisions. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*/deployments/*}/revisions', + }, + ] + request, metadata = self._interceptor.pre_list_revisions(request, metadata) + pb_request = config.ListRevisionsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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) + return resp + + class _LockDeployment(ConfigRestStub): + def __hash__(self): + return hash("LockDeployment") + + __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} + + def __call__(self, + request: config.LockDeploymentRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{name=projects/*/locations/*/deployments/*}:lock', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_lock_deployment(request, metadata) + pb_request = config.LockDeploymentRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=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) + return resp + + class _UnlockDeployment(ConfigRestStub): + def __hash__(self): + return hash("UnlockDeployment") + + __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} + + def __call__(self, + request: config.UnlockDeploymentRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{name=projects/*/locations/*/deployments/*}:unlock', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_unlock_deployment(request, metadata) + pb_request = config.UnlockDeploymentRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=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) + return resp + + class _UpdateDeployment(ConfigRestStub): + def __hash__(self): + return hash("UpdateDeployment") + + __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} + + def __call__(self, + request: config.UpdateDeploymentRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{deployment.name=projects/*/locations/*/deployments/*}', + 'body': 'deployment', + }, + ] + request, metadata = self._interceptor.pre_update_deployment(request, metadata) + pb_request = config.UpdateDeploymentRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=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) + 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_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 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_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 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(ConfigRestStub): + def __call__(self, + request: locations_pb2.GetLocationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + locations_pb2.Location: Response from GetLocation method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*}', + }, + ] + + request, metadata = self._interceptor.pre_get_location(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = locations_pb2.Location() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_location(resp) + return resp + + @property + def list_locations(self): + return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore + + class _ListLocations(ConfigRestStub): + def __call__(self, + request: locations_pb2.ListLocationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + locations_pb2.ListLocationsResponse: Response from ListLocations method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*}/locations', + }, + ] + + request, metadata = self._interceptor.pre_list_locations(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = locations_pb2.ListLocationsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_list_locations(resp) + return resp + + @property + def get_iam_policy(self): + return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _GetIamPolicy(ConfigRestStub): + def __call__(self, + request: iam_policy_pb2.GetIamPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + policy_pb2.Policy: Response from GetIamPolicy method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{resource=projects/*/locations/*/deployments/*}:getIamPolicy', + }, + ] + + request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = policy_pb2.Policy() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_iam_policy(resp) + return resp + + @property + def set_iam_policy(self): + return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _SetIamPolicy(ConfigRestStub): + def __call__(self, + request: iam_policy_pb2.SetIamPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + policy_pb2.Policy: Response from SetIamPolicy method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/deployments/*}:setIamPolicy', + 'body': '*', + }, + ] + + request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + body = json.dumps(transcoded_request['body']) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + data=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) + + resp = policy_pb2.Policy() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_set_iam_policy(resp) + return resp + + @property + def test_iam_permissions(self): + return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore + + class _TestIamPermissions(ConfigRestStub): + def __call__(self, + request: iam_policy_pb2.TestIamPermissionsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + iam_policy_pb2.TestIamPermissionsResponse: Response from TestIamPermissions method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/deployments/*}:testIamPermissions', + 'body': '*', + }, + ] + + request, metadata = self._interceptor.pre_test_iam_permissions(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + body = json.dumps(transcoded_request['body']) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + data=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) + + resp = iam_policy_pb2.TestIamPermissionsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_test_iam_permissions(resp) + return resp + + @property + def cancel_operation(self): + return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore + + class _CancelOperation(ConfigRestStub): + def __call__(self, + request: operations_pb2.CancelOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}:cancel', + 'body': '*', + }, + ] + + request, metadata = self._interceptor.pre_cancel_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + body = json.dumps(transcoded_request['body']) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + data=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(ConfigRestStub): + def __call__(self, + request: operations_pb2.DeleteOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + }, + ] + + request, metadata = self._interceptor.pre_delete_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # 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(ConfigRestStub): + def __call__(self, + request: operations_pb2.GetOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + }, + ] + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.Operation() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_operation(resp) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations(ConfigRestStub): + def __call__(self, + request: operations_pb2.ListOperationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.ListOperationsResponse: Response from ListOperations method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*}/operations', + }, + ] + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_list_operations(resp) + 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/types/__init__.py b/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/types/__init__.py new file mode 100644 index 000000000000..8c07419e7426 --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/types/__init__.py @@ -0,0 +1,110 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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, + GetResourceRequest, + GetRevisionRequest, + GitSource, + ImportStatefileRequest, + ListDeploymentsRequest, + ListDeploymentsResponse, + ListPreviewsRequest, + ListPreviewsResponse, + ListResourcesRequest, + ListResourcesResponse, + ListRevisionsRequest, + ListRevisionsResponse, + LockDeploymentRequest, + LockInfo, + OperationMetadata, + Preview, + PreviewArtifacts, + PreviewOperationMetadata, + PreviewResult, + Resource, + ResourceCAIInfo, + ResourceTerraformInfo, + Revision, + Statefile, + TerraformBlueprint, + TerraformError, + TerraformOutput, + TerraformVariable, + UnlockDeploymentRequest, + UpdateDeploymentRequest, +) + +__all__ = ( + 'ApplyResults', + 'CreateDeploymentRequest', + 'CreatePreviewRequest', + 'DeleteDeploymentRequest', + 'DeletePreviewRequest', + 'DeleteStatefileRequest', + 'Deployment', + 'DeploymentOperationMetadata', + 'ExportDeploymentStatefileRequest', + 'ExportLockInfoRequest', + 'ExportPreviewResultRequest', + 'ExportPreviewResultResponse', + 'ExportRevisionStatefileRequest', + 'GetDeploymentRequest', + 'GetPreviewRequest', + 'GetResourceRequest', + 'GetRevisionRequest', + 'GitSource', + 'ImportStatefileRequest', + 'ListDeploymentsRequest', + 'ListDeploymentsResponse', + 'ListPreviewsRequest', + 'ListPreviewsResponse', + 'ListResourcesRequest', + 'ListResourcesResponse', + 'ListRevisionsRequest', + 'ListRevisionsResponse', + 'LockDeploymentRequest', + 'LockInfo', + 'OperationMetadata', + 'Preview', + 'PreviewArtifacts', + 'PreviewOperationMetadata', + 'PreviewResult', + 'Resource', + 'ResourceCAIInfo', + 'ResourceTerraformInfo', + 'Revision', + 'Statefile', + 'TerraformBlueprint', + 'TerraformError', + 'TerraformOutput', + 'TerraformVariable', + 'UnlockDeploymentRequest', + 'UpdateDeploymentRequest', +) 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..e3ac91093f6b --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/types/config.py @@ -0,0 +1,2442 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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={ + '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', + }, +) + + +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): + 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]): + 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): + Optional. 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. + """ + 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, + ) + + +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): + Required. 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): + Required. URI of a public Git repo. + + This field is a member of `oneof`_ ``source``. + input_values (MutableMapping[str, google.cloud.config_v1.types.TerraformVariable]): + 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): + 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 or set to 0, + all resources will be returned. + 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 or set to 0, + all resources will be returned. + 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 [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. + """ + 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. + """ + ERROR_CODE_UNSPECIFIED = 0 + CLOUD_BUILD_PERMISSION_DENIED = 1 + APPLY_BUILD_API_FAILED = 4 + APPLY_BUILD_RUN_FAILED = 5 + + 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, + ) + + +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): + 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 + """ + 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 + + 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 or set to 0, + all resources will be returned. + 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][]s. + 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): + Optional. Optional service account. If + omitted, the deployment resource reference must + be provided, and the service account attached to + the deployment will be used. + 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. + """ + 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, + ) + + +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. + """ + 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 + + 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 or + set to 0, all resources will be returned. + 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][]s. + 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, + ) + + +__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..d57180871112 --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/noxfile.py @@ -0,0 +1,177 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 shutil +import subprocess +import sys + + +import nox # type: ignore + +ALL_PYTHON = [ + "3.7", + "3.8", + "3.9", + "3.10", + "3.11", + "3.12" +] + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" +PACKAGE_NAME = 'google-cloud-config' + +BLACK_VERSION = "black==22.3.0" +BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] +DEFAULT_PYTHON_VERSION = "3.12" + +nox.sessions = [ + "unit", + "cover", + "mypy", + "check_lower_bounds" + # exclude update_lower_bounds from default + "docs", + "blacken", + "lint", +] + +@nox.session(python=ALL_PYTHON) +def unit(session): + """Run the unit test suite.""" + + session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + session.install('-e', '.') + + session.run( + 'py.test', + '--quiet', + '--cov=google/cloud/config_v1/', + '--cov=tests/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(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=ALL_PYTHON) +def mypy(session): + """Run the type checker.""" + session.install( + 'mypy', + '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 docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install("sphinx==7.0.1", "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", + "-d", + os.path.join("docs", "_build", "doctrees", ""), + os.path.join("docs", ""), + os.path.join("docs", "_build", "html", ""), + ) + + +@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", + *BLACK_PATHS, + ) + session.run("flake8", "google", "tests", "samples") + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def blacken(session): + """Run black. Format code to uniform standard.""" + session.install(BLACK_VERSION) + session.run( + "black", + *BLACK_PATHS, + ) 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..9f5a6f8d4515 --- /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 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..4ff94956cc0b --- /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 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..16fcc030958b --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_create_preview_async.py @@ -0,0 +1,60 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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" + + 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..db581ef7d92b --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_create_preview_sync.py @@ -0,0 +1,60 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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" + + 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..866144f716af --- /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 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..198ecc75583f --- /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 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..e0582077006b --- /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 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..4b79b21e5600 --- /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 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..9b29aaeda1cc --- /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 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..0e0bff321bfd --- /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 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..9ddc0b71e08b --- /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 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..de50f1469e96 --- /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 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..618eccf6031e --- /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 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..9dc042354cbb --- /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 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..4ed8c1b5b82b --- /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 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..e5b314c834fa --- /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 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..cb5c02d7d650 --- /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 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..c101b8f3554f --- /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 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..12d9da8c4d41 --- /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 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..29877f5621c2 --- /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 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..e27ee6bbb74c --- /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 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..746f326e3a5b --- /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 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..5af489c3823a --- /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 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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_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..c010cc9b97b3 --- /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 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..cbbbedb33498 --- /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 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..95ef695541a5 --- /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 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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_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..93d7e21bed32 --- /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 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..4fdbe2b26933 --- /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 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..0e610caebe93 --- /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 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..dac0a9c6e11e --- /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 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..76176272ca92 --- /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 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..b781dfa7f067 --- /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 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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_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..4ce4fa8fe6fd --- /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 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..620e9bf97485 --- /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 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..0403d42efd50 --- /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 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..42746c70dd18 --- /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 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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_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..4bad83dff4e0 --- /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 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..d706b4f4fe8c --- /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 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..f0ec2cf6aa7d --- /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 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..a0e78638e712 --- /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 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..7d705d83d6b9 --- /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 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..3ae193bf307c --- /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 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..9f9d26c92521 --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/snippet_metadata_google.cloud.config.v1.json @@ -0,0 +1,3414 @@ +{ + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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": 59, + "start": 27, + "type": "FULL" + }, + { + "end": 59, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 56, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 60, + "start": 57, + "type": "RESPONSE_HANDLING" + } + ], + "title": "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, str]" + } + ], + "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": 59, + "start": 27, + "type": "FULL" + }, + { + "end": 59, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 56, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 60, + "start": 57, + "type": "RESPONSE_HANDLING" + } + ], + "title": "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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", + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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.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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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_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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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.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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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..c9978014e855 --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/scripts/fixup_config_v1_keywords.py @@ -0,0 +1,196 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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_revision': ('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_resources': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), + 'list_revisions': ('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..80cc751f2ff4 --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/setup.py @@ -0,0 +1,91 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.0, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", + "proto-plus >= 1.22.3, <2.0.0dev", + "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", + "grpc-google-iam-v1 >= 0.12.4, <1.0.0dev", +] +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", + "Operating System :: OS Independent", + "Topic :: Internet", + ], + platforms="Posix; MacOS X; Windows", + packages=packages, + python_requires=">=3.7", + install_requires=dependencies, + 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.7.txt b/owl-bot-staging/google-cloud-config/v1/testing/constraints-3.7.txt new file mode 100644 index 000000000000..44ffd04543a8 --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/testing/constraints-3.7.txt @@ -0,0 +1,10 @@ +# 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.0dev", +# Then this file should have google-cloud-foo==1.14.0 +google-api-core==1.34.0 +proto-plus==1.22.3 +protobuf==3.19.5 +grpc-google-iam-v1==0.12.4 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..1b4db446eb8d --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..1b4db446eb8d --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..1b4db446eb8d --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..1b4db446eb8d --- /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 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..bc7c39e1f8c4 --- /dev/null +++ b/owl-bot-staging/google-cloud-config/v1/tests/unit/gapic/config_v1/test_config.py @@ -0,0 +1,14019 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 +from google.protobuf import json_format +import json +import math +import pytest +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 + +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.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 + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# 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 + + +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 + + +@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", modify_default_endpoint(ConfigClient)) +@mock.patch.object(ConfigAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(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, + 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): + client = client_class(transport=transport_name) + + # 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): + client = client_class(transport=transport_name) + + # 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, + 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, + 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", modify_default_endpoint(ConfigClient)) +@mock.patch.object(ConfigAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(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 + 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 + 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, + 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 + + +@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, + 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, + 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, + 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] + assert args[0] == config.ListDeploymentsRequest() + + # 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_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_deployments), + '__call__') as call: + client.list_deployments() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == config.ListDeploymentsRequest() + +@pytest.mark.asyncio +async def test_list_deployments_async(transport: str = 'grpc_asyncio', request_type=config.ListDeploymentsRequest): + client = ConfigAsyncClient( + 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 =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] + assert args[0] == config.ListDeploymentsRequest() + + # 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=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 = 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=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.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=ga_credentials.AnonymousCredentials(), + ) + + # 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, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_deployments(request={}) + + assert pager._metadata == metadata + + 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=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__', 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=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__', 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, + ) + 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] + assert args[0] == config.GetDeploymentRequest() + + # 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 + + +def test_get_deployment_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_deployment), + '__call__') as call: + client.get_deployment() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == config.GetDeploymentRequest() + +@pytest.mark.asyncio +async def test_get_deployment_async(transport: str = 'grpc_asyncio', request_type=config.GetDeploymentRequest): + client = ConfigAsyncClient( + 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 =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, + )) + 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] + assert args[0] == config.GetDeploymentRequest() + + # 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 + + +@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=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 = 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=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.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=ga_credentials.AnonymousCredentials(), + ) + + # 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] + assert args[0] == config.CreateDeploymentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_deployment_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_deployment), + '__call__') as call: + client.create_deployment() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == config.CreateDeploymentRequest() + +@pytest.mark.asyncio +async def test_create_deployment_async(transport: str = 'grpc_asyncio', request_type=config.CreateDeploymentRequest): + client = ConfigAsyncClient( + 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 = 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] + assert args[0] == config.CreateDeploymentRequest() + + # 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=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 = 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=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.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=ga_credentials.AnonymousCredentials(), + ) + + # 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] + assert args[0] == config.UpdateDeploymentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_deployment_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_deployment), + '__call__') as call: + client.update_deployment() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == config.UpdateDeploymentRequest() + +@pytest.mark.asyncio +async def test_update_deployment_async(transport: str = 'grpc_asyncio', request_type=config.UpdateDeploymentRequest): + client = ConfigAsyncClient( + 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 = 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] + assert args[0] == config.UpdateDeploymentRequest() + + # 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=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 = 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=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.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=ga_credentials.AnonymousCredentials(), + ) + + # 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] + assert args[0] == config.DeleteDeploymentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_deployment_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_deployment), + '__call__') as call: + client.delete_deployment() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == config.DeleteDeploymentRequest() + +@pytest.mark.asyncio +async def test_delete_deployment_async(transport: str = 'grpc_asyncio', request_type=config.DeleteDeploymentRequest): + client = ConfigAsyncClient( + 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 = 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] + assert args[0] == config.DeleteDeploymentRequest() + + # 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=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 = 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=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.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=ga_credentials.AnonymousCredentials(), + ) + + # 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] + assert args[0] == config.ListRevisionsRequest() + + # 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_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_revisions), + '__call__') as call: + client.list_revisions() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == config.ListRevisionsRequest() + +@pytest.mark.asyncio +async def test_list_revisions_async(transport: str = 'grpc_asyncio', request_type=config.ListRevisionsRequest): + client = ConfigAsyncClient( + 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 =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] + assert args[0] == config.ListRevisionsRequest() + + # 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=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 = 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=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.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=ga_credentials.AnonymousCredentials(), + ) + + # 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, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_revisions(request={}) + + assert pager._metadata == metadata + + 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=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__', 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=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__', 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', + ) + 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] + assert args[0] == config.GetRevisionRequest() + + # 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' + + +def test_get_revision_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_revision), + '__call__') as call: + client.get_revision() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == config.GetRevisionRequest() + +@pytest.mark.asyncio +async def test_get_revision_async(transport: str = 'grpc_asyncio', request_type=config.GetRevisionRequest): + client = ConfigAsyncClient( + 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 =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', + )) + 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] + assert args[0] == config.GetRevisionRequest() + + # 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' + + +@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=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 = 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=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.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=ga_credentials.AnonymousCredentials(), + ) + + # 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] + assert args[0] == config.GetResourceRequest() + + # 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_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_resource), + '__call__') as call: + client.get_resource() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == config.GetResourceRequest() + +@pytest.mark.asyncio +async def test_get_resource_async(transport: str = 'grpc_asyncio', request_type=config.GetResourceRequest): + client = ConfigAsyncClient( + 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 =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] + assert args[0] == config.GetResourceRequest() + + # 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=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 = 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=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.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=ga_credentials.AnonymousCredentials(), + ) + + # 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] + assert args[0] == config.ListResourcesRequest() + + # 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_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_resources), + '__call__') as call: + client.list_resources() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == config.ListResourcesRequest() + +@pytest.mark.asyncio +async def test_list_resources_async(transport: str = 'grpc_asyncio', request_type=config.ListResourcesRequest): + client = ConfigAsyncClient( + 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 =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] + assert args[0] == config.ListResourcesRequest() + + # 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=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 = 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=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.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=ga_credentials.AnonymousCredentials(), + ) + + # 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, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_resources(request={}) + + assert pager._metadata == metadata + + 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=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__', 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=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__', 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] + assert args[0] == config.ExportDeploymentStatefileRequest() + + # 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_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # 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: + client.export_deployment_statefile() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == config.ExportDeploymentStatefileRequest() + +@pytest.mark.asyncio +async def test_export_deployment_statefile_async(transport: str = 'grpc_asyncio', request_type=config.ExportDeploymentStatefileRequest): + client = ConfigAsyncClient( + 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 =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] + assert args[0] == config.ExportDeploymentStatefileRequest() + + # 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=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 = 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] + assert args[0] == config.ExportRevisionStatefileRequest() + + # 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_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # 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: + client.export_revision_statefile() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == config.ExportRevisionStatefileRequest() + +@pytest.mark.asyncio +async def test_export_revision_statefile_async(transport: str = 'grpc_asyncio', request_type=config.ExportRevisionStatefileRequest): + client = ConfigAsyncClient( + 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 =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] + assert args[0] == config.ExportRevisionStatefileRequest() + + # 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=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 = 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] + assert args[0] == config.ImportStatefileRequest() + + # 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_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_statefile), + '__call__') as call: + client.import_statefile() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == config.ImportStatefileRequest() + +@pytest.mark.asyncio +async def test_import_statefile_async(transport: str = 'grpc_asyncio', request_type=config.ImportStatefileRequest): + client = ConfigAsyncClient( + 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 =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] + assert args[0] == config.ImportStatefileRequest() + + # 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=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 = 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=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.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=ga_credentials.AnonymousCredentials(), + ) + + # 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] + assert args[0] == config.DeleteStatefileRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_statefile_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_statefile), + '__call__') as call: + client.delete_statefile() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == config.DeleteStatefileRequest() + +@pytest.mark.asyncio +async def test_delete_statefile_async(transport: str = 'grpc_asyncio', request_type=config.DeleteStatefileRequest): + client = ConfigAsyncClient( + 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 = 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] + assert args[0] == config.DeleteStatefileRequest() + + # 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=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 = 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=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.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=ga_credentials.AnonymousCredentials(), + ) + + # 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] + assert args[0] == config.LockDeploymentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_lock_deployment_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.lock_deployment), + '__call__') as call: + client.lock_deployment() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == config.LockDeploymentRequest() + +@pytest.mark.asyncio +async def test_lock_deployment_async(transport: str = 'grpc_asyncio', request_type=config.LockDeploymentRequest): + client = ConfigAsyncClient( + 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 = 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] + assert args[0] == config.LockDeploymentRequest() + + # 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=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 = 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=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.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=ga_credentials.AnonymousCredentials(), + ) + + # 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] + assert args[0] == config.UnlockDeploymentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_unlock_deployment_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.unlock_deployment), + '__call__') as call: + client.unlock_deployment() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == config.UnlockDeploymentRequest() + +@pytest.mark.asyncio +async def test_unlock_deployment_async(transport: str = 'grpc_asyncio', request_type=config.UnlockDeploymentRequest): + client = ConfigAsyncClient( + 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 = 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] + assert args[0] == config.UnlockDeploymentRequest() + + # 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=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 = 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=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.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=ga_credentials.AnonymousCredentials(), + ) + + # 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] + assert args[0] == config.ExportLockInfoRequest() + + # 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_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # 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: + client.export_lock_info() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == config.ExportLockInfoRequest() + +@pytest.mark.asyncio +async def test_export_lock_info_async(transport: str = 'grpc_asyncio', request_type=config.ExportLockInfoRequest): + client = ConfigAsyncClient( + 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 =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] + assert args[0] == config.ExportLockInfoRequest() + + # 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=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 = 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=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.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=ga_credentials.AnonymousCredentials(), + ) + + # 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] + assert args[0] == config.CreatePreviewRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_preview_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_preview), + '__call__') as call: + client.create_preview() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == config.CreatePreviewRequest() + +@pytest.mark.asyncio +async def test_create_preview_async(transport: str = 'grpc_asyncio', request_type=config.CreatePreviewRequest): + client = ConfigAsyncClient( + 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 = 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] + assert args[0] == config.CreatePreviewRequest() + + # 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=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 = 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=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.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=ga_credentials.AnonymousCredentials(), + ) + + # 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', + ) + 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] + assert args[0] == config.GetPreviewRequest() + + # 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' + + +def test_get_preview_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_preview), + '__call__') as call: + client.get_preview() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == config.GetPreviewRequest() + +@pytest.mark.asyncio +async def test_get_preview_async(transport: str = 'grpc_asyncio', request_type=config.GetPreviewRequest): + client = ConfigAsyncClient( + 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 =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', + )) + 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] + assert args[0] == config.GetPreviewRequest() + + # 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' + + +@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=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 = 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=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.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=ga_credentials.AnonymousCredentials(), + ) + + # 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] + assert args[0] == config.ListPreviewsRequest() + + # 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_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_previews), + '__call__') as call: + client.list_previews() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == config.ListPreviewsRequest() + +@pytest.mark.asyncio +async def test_list_previews_async(transport: str = 'grpc_asyncio', request_type=config.ListPreviewsRequest): + client = ConfigAsyncClient( + 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 =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] + assert args[0] == config.ListPreviewsRequest() + + # 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=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 = 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=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.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=ga_credentials.AnonymousCredentials(), + ) + + # 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, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_previews(request={}) + + assert pager._metadata == metadata + + 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=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__', 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=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__', 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] + assert args[0] == config.DeletePreviewRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_preview_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_preview), + '__call__') as call: + client.delete_preview() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == config.DeletePreviewRequest() + +@pytest.mark.asyncio +async def test_delete_preview_async(transport: str = 'grpc_asyncio', request_type=config.DeletePreviewRequest): + client = ConfigAsyncClient( + 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 = 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] + assert args[0] == config.DeletePreviewRequest() + + # 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=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 = 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=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.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=ga_credentials.AnonymousCredentials(), + ) + + # 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] + assert args[0] == config.ExportPreviewResultRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, config.ExportPreviewResultResponse) + + +def test_export_preview_result_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # 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: + client.export_preview_result() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == config.ExportPreviewResultRequest() + +@pytest.mark.asyncio +async def test_export_preview_result_async(transport: str = 'grpc_asyncio', request_type=config.ExportPreviewResultRequest): + client = ConfigAsyncClient( + 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 =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] + assert args[0] == config.ExportPreviewResultRequest() + + # 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=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 = 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.ListDeploymentsRequest, + dict, +]) +def test_list_deployments_rest(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 = 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 + 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'] + + +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, + including_default_value_fields=False, + 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 + + 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", ))) + + +@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, "pre_list_deployments") as pre: + pre.assert_not_called() + post.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 = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = config.ListDeploymentsResponse.to_json(config.ListDeploymentsResponse()) + + request = config.ListDeploymentsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = config.ListDeploymentsResponse() + + client.list_deployments(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_deployments_rest_bad_request(transport: str = 'rest', request_type=config.ListDeploymentsRequest): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_deployments(request) + + +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 + + 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 + + +@pytest.mark.parametrize("request_type", [ + config.GetDeploymentRequest, + dict, +]) +def test_get_deployment_rest(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, + ) + + # 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 + 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 + + +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, + including_default_value_fields=False, + 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 + + 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", ))) + + +@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, "pre_get_deployment") as pre: + pre.assert_not_called() + post.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 = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = config.Deployment.to_json(config.Deployment()) + + request = config.GetDeploymentRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = config.Deployment() + + client.get_deployment(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_deployment_rest_bad_request(transport: str = 'rest', request_type=config.GetDeploymentRequest): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_deployment(request) + + +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 + + 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_get_deployment_rest_error(): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + config.CreateDeploymentRequest, + dict, +]) +def test_create_deployment_rest(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} + # 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 = 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 + response = client.create_deployment(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +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, + including_default_value_fields=False, + 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 + + 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", ))) + + +@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, "pre_create_deployment") as pre: + pre.assert_not_called() + post.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 = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = config.CreateDeploymentRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_deployment(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_deployment_rest_bad_request(transport: str = 'rest', request_type=config.CreateDeploymentRequest): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_deployment(request) + + +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 + + 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_create_deployment_rest_error(): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + config.UpdateDeploymentRequest, + dict, +]) +def test_update_deployment_rest(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} + # 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 = 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 + response = client.update_deployment(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +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, + including_default_value_fields=False, + 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 + + 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", ))) + + +@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, "pre_update_deployment") as pre: + pre.assert_not_called() + post.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 = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = config.UpdateDeploymentRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_deployment(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_deployment_rest_bad_request(transport: str = 'rest', request_type=config.UpdateDeploymentRequest): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_deployment(request) + + +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 + + 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_update_deployment_rest_error(): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + config.DeleteDeploymentRequest, + dict, +]) +def test_delete_deployment_rest(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 = 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 + response = client.delete_deployment(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +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, + including_default_value_fields=False, + 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 + + 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", ))) + + +@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, "pre_delete_deployment") as pre: + pre.assert_not_called() + post.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 = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = config.DeleteDeploymentRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_deployment(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_deployment_rest_bad_request(transport: str = 'rest', request_type=config.DeleteDeploymentRequest): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_deployment(request) + + +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 + + 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_delete_deployment_rest_error(): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + config.ListRevisionsRequest, + dict, +]) +def test_list_revisions_rest(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 = 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 + 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'] + + +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, + including_default_value_fields=False, + 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 + + 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", ))) + + +@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, "pre_list_revisions") as pre: + pre.assert_not_called() + post.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 = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = config.ListRevisionsResponse.to_json(config.ListRevisionsResponse()) + + request = config.ListRevisionsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = config.ListRevisionsResponse() + + client.list_revisions(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_revisions_rest_bad_request(transport: str = 'rest', request_type=config.ListRevisionsRequest): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_revisions(request) + + +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 + + 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 + + +@pytest.mark.parametrize("request_type", [ + config.GetRevisionRequest, + dict, +]) +def test_get_revision_rest(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', + ) + + # 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 + 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' + + +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, + including_default_value_fields=False, + 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 + + 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", ))) + + +@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, "pre_get_revision") as pre: + pre.assert_not_called() + post.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 = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = config.Revision.to_json(config.Revision()) + + request = config.GetRevisionRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = config.Revision() + + client.get_revision(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_revision_rest_bad_request(transport: str = 'rest', request_type=config.GetRevisionRequest): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_revision(request) + + +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 + + 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_revision_rest_error(): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + config.GetResourceRequest, + dict, +]) +def test_get_resource_rest(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 = 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 + 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 + + +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, + including_default_value_fields=False, + 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 + + 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", ))) + + +@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, "pre_get_resource") as pre: + pre.assert_not_called() + post.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 = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = config.Resource.to_json(config.Resource()) + + request = config.GetResourceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = config.Resource() + + client.get_resource(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_resource_rest_bad_request(transport: str = 'rest', request_type=config.GetResourceRequest): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_resource(request) + + +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 + + 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_get_resource_rest_error(): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + config.ListResourcesRequest, + dict, +]) +def test_list_resources_rest(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 = 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 + 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'] + + +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, + including_default_value_fields=False, + 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 + + 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", ))) + + +@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, "pre_list_resources") as pre: + pre.assert_not_called() + post.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 = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = config.ListResourcesResponse.to_json(config.ListResourcesResponse()) + + request = config.ListResourcesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = config.ListResourcesResponse() + + client.list_resources(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_resources_rest_bad_request(transport: str = 'rest', request_type=config.ListResourcesRequest): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_resources(request) + + +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 + + 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 + + +@pytest.mark.parametrize("request_type", [ + config.ExportDeploymentStatefileRequest, + dict, +]) +def test_export_deployment_statefile_rest(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 = 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 + 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' + + +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, + including_default_value_fields=False, + 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 + + 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", ))) + + +@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, "pre_export_deployment_statefile") as pre: + pre.assert_not_called() + post.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 = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = config.Statefile.to_json(config.Statefile()) + + request = config.ExportDeploymentStatefileRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = config.Statefile() + + client.export_deployment_statefile(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_export_deployment_statefile_rest_bad_request(transport: str = 'rest', request_type=config.ExportDeploymentStatefileRequest): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.export_deployment_statefile(request) + + +def test_export_deployment_statefile_rest_error(): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + config.ExportRevisionStatefileRequest, + dict, +]) +def test_export_revision_statefile_rest(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 = 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 + 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' + + +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, + including_default_value_fields=False, + 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 + + 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", ))) + + +@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, "pre_export_revision_statefile") as pre: + pre.assert_not_called() + post.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 = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = config.Statefile.to_json(config.Statefile()) + + request = config.ExportRevisionStatefileRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = config.Statefile() + + client.export_revision_statefile(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_export_revision_statefile_rest_bad_request(transport: str = 'rest', request_type=config.ExportRevisionStatefileRequest): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.export_revision_statefile(request) + + +def test_export_revision_statefile_rest_error(): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + config.ImportStatefileRequest, + dict, +]) +def test_import_statefile_rest(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 = 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 + 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' + + +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, + including_default_value_fields=False, + 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 + + 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", ))) + + +@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, "pre_import_statefile") as pre: + pre.assert_not_called() + post.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 = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = config.Statefile.to_json(config.Statefile()) + + request = config.ImportStatefileRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = config.Statefile() + + client.import_statefile(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_import_statefile_rest_bad_request(transport: str = 'rest', request_type=config.ImportStatefileRequest): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.import_statefile(request) + + +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 + + 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_import_statefile_rest_error(): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + config.DeleteStatefileRequest, + dict, +]) +def test_delete_statefile_rest(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 = Response() + response_value.status_code = 200 + json_return_value = '' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.delete_statefile(request) + + # Establish that the response is the type that we expect. + assert response is None + + +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, + including_default_value_fields=False, + 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 + + 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", ))) + + +@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 = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + + 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_delete_statefile_rest_bad_request(transport: str = 'rest', request_type=config.DeleteStatefileRequest): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_statefile(request) + + +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 + + 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_delete_statefile_rest_error(): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + config.LockDeploymentRequest, + dict, +]) +def test_lock_deployment_rest(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 = 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 + response = client.lock_deployment(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +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, + including_default_value_fields=False, + 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 + + 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", ))) + + +@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, "pre_lock_deployment") as pre: + pre.assert_not_called() + post.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 = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = config.LockDeploymentRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.lock_deployment(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_lock_deployment_rest_bad_request(transport: str = 'rest', request_type=config.LockDeploymentRequest): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.lock_deployment(request) + + +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 + + 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_lock_deployment_rest_error(): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + config.UnlockDeploymentRequest, + dict, +]) +def test_unlock_deployment_rest(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 = 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 + response = client.unlock_deployment(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +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, + including_default_value_fields=False, + 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 + + 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", ))) + + +@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, "pre_unlock_deployment") as pre: + pre.assert_not_called() + post.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 = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = config.UnlockDeploymentRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.unlock_deployment(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_unlock_deployment_rest_bad_request(transport: str = 'rest', request_type=config.UnlockDeploymentRequest): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.unlock_deployment(request) + + +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 + + 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_unlock_deployment_rest_error(): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + config.ExportLockInfoRequest, + dict, +]) +def test_export_lock_info_rest(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 = 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 + 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' + + +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, + including_default_value_fields=False, + 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 + + 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", ))) + + +@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, "pre_export_lock_info") as pre: + pre.assert_not_called() + post.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 = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = config.LockInfo.to_json(config.LockInfo()) + + request = config.ExportLockInfoRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = config.LockInfo() + + client.export_lock_info(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_export_lock_info_rest_bad_request(transport: str = 'rest', request_type=config.ExportLockInfoRequest): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.export_lock_info(request) + + +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 + + 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_export_lock_info_rest_error(): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + config.CreatePreviewRequest, + dict, +]) +def test_create_preview_rest(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'} + # 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 = 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 + response = client.create_preview(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +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, + including_default_value_fields=False, + 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 + + 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", ))) + + +@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, "pre_create_preview") as pre: + pre.assert_not_called() + post.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 = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = config.CreatePreviewRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_preview(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_preview_rest_bad_request(transport: str = 'rest', request_type=config.CreatePreviewRequest): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_preview(request) + + +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 + + 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_create_preview_rest_error(): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + config.GetPreviewRequest, + dict, +]) +def test_get_preview_rest(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', + ) + + # 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 + 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' + + +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, + including_default_value_fields=False, + 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 + + 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", ))) + + +@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, "pre_get_preview") as pre: + pre.assert_not_called() + post.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 = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = config.Preview.to_json(config.Preview()) + + request = config.GetPreviewRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = config.Preview() + + client.get_preview(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_preview_rest_bad_request(transport: str = 'rest', request_type=config.GetPreviewRequest): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_preview(request) + + +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 + + 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_get_preview_rest_error(): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + config.ListPreviewsRequest, + dict, +]) +def test_list_previews_rest(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 = 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 + 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'] + + +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, + including_default_value_fields=False, + 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 + + 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", ))) + + +@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, "pre_list_previews") as pre: + pre.assert_not_called() + post.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 = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = config.ListPreviewsResponse.to_json(config.ListPreviewsResponse()) + + request = config.ListPreviewsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = config.ListPreviewsResponse() + + client.list_previews(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_previews_rest_bad_request(transport: str = 'rest', request_type=config.ListPreviewsRequest): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_previews(request) + + +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 + + 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 + + +@pytest.mark.parametrize("request_type", [ + config.DeletePreviewRequest, + dict, +]) +def test_delete_preview_rest(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 = 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 + response = client.delete_preview(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +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, + including_default_value_fields=False, + 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 + + 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", ))) + + +@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, "pre_delete_preview") as pre: + pre.assert_not_called() + post.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 = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = config.DeletePreviewRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_preview(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_preview_rest_bad_request(transport: str = 'rest', request_type=config.DeletePreviewRequest): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_preview(request) + + +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 + + 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_delete_preview_rest_error(): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + config.ExportPreviewResultRequest, + dict, +]) +def test_export_preview_result_rest(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 = 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 + response = client.export_preview_result(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, config.ExportPreviewResultResponse) + + +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, + including_default_value_fields=False, + 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 + + 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", ))) + + +@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, "pre_export_preview_result") as pre: + pre.assert_not_called() + post.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 = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = config.ExportPreviewResultResponse.to_json(config.ExportPreviewResultResponse()) + + request = config.ExportPreviewResultRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = config.ExportPreviewResultResponse() + + client.export_preview_result(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_export_preview_result_rest_bad_request(transport: str = 'rest', request_type=config.ExportPreviewResultRequest): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.export_preview_result(request) + + +def test_export_preview_result_rest_error(): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +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 = mock.Mock() + 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() + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "rest", +]) +def test_transport_kind(transport_name): + transport = ConfigClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + +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', + '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) + + +def test_config_rest_lro_client(): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + transport = client.transport + + # Ensure that we have a 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 + + +@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 +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_revision_path(): + project = "scallop" + location = "abalone" + deployment = "squid" + revision = "clam" + 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": "whelk", + "location": "octopus", + "deployment": "oyster", + "revision": "nudibranch", + } + 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 = "cuttlefish" + service_account = "mussel" + 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": "winkle", + "service_account": "nautilus", + } + 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_worker_pool_path(): + project = "scallop" + location = "abalone" + worker_pool = "squid" + 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": "clam", + "location": "whelk", + "worker_pool": "octopus", + } + 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 = "oyster" + 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": "nudibranch", + } + 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 = "cuttlefish" + expected = "folders/{folder}".format(folder=folder, ) + actual = ConfigClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "mussel", + } + 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 = "winkle" + expected = "organizations/{organization}".format(organization=organization, ) + actual = ConfigClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nautilus", + } + 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 = "scallop" + expected = "projects/{project}".format(project=project, ) + actual = ConfigClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "abalone", + } + 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 = "squid" + location = "clam" + 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": "whelk", + "location": "octopus", + } + 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) + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = ConfigAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + 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_get_location_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.GetLocationRequest): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + 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(type(client.transport._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 = 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 + + 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(transport: str = 'rest', request_type=locations_pb2.ListLocationsRequest): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + 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(type(client.transport._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 = 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 + + 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(transport: str = 'rest', request_type=iam_policy_pb2.GetIamPolicyRequest): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + 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(type(client.transport._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 = 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 + + 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(transport: str = 'rest', request_type=iam_policy_pb2.SetIamPolicyRequest): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + 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(type(client.transport._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 = 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 + + 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(transport: str = 'rest', request_type=iam_policy_pb2.TestIamPermissionsRequest): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + 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(type(client.transport._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 = 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 + + 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(transport: str = 'rest', request_type=operations_pb2.CancelOperationRequest): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + 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(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 = Response() + response_value.status_code = 200 + json_return_value = '{}' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + 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(transport: str = 'rest', request_type=operations_pb2.DeleteOperationRequest): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + 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(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 = Response() + response_value.status_code = 200 + json_return_value = '{}' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + 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(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + 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(type(client.transport._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 = 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 + + 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(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + 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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + 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(type(client.transport._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 = 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 + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +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=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 = 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=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 = 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=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 = 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=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 = 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=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 = 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=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 = 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=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 = 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=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 = 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=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 = 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=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 = 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=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 = 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=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 = 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=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 = 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=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 = 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=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 = 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=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 = 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=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 = 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=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 = 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=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. + # 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=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 = 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=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 = 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=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 = 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=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 = 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=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 = 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=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 = 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=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 = 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=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 = 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(): + transports = { + "rest": "_session", + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "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, + 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 b1ba1cf5bf0dc45e95a6d19e938b98cd8831ddd8 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Sat, 13 Jan 2024 01:25:28 +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 | 33 - .../google-cloud-config/v1/MANIFEST.in | 2 - .../google-cloud-config/v1/README.rst | 49 - .../v1/docs/_static/custom.css | 3 - .../google-cloud-config/v1/docs/conf.py | 376 - .../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 | 7 - .../v1/google/cloud/config/__init__.py | 117 - .../v1/google/cloud/config/gapic_version.py | 16 - .../v1/google/cloud/config/py.typed | 2 - .../v1/google/cloud/config_v1/__init__.py | 118 - .../cloud/config_v1/gapic_metadata.json | 343 - .../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 | 3119 ---- .../cloud/config_v1/services/config/client.py | 3366 ---- .../cloud/config_v1/services/config/pagers.py | 502 - .../services/config/transports/__init__.py | 38 - .../services/config/transports/base.py | 521 - .../services/config/transports/grpc.py | 1005 -- .../config/transports/grpc_asyncio.py | 1004 -- .../services/config/transports/rest.py | 3431 ---- .../google/cloud/config_v1/types/__init__.py | 110 - .../v1/google/cloud/config_v1/types/config.py | 2442 --- .../google-cloud-config/v1/mypy.ini | 3 - .../google-cloud-config/v1/noxfile.py | 177 - ...enerated_config_create_deployment_async.py | 61 - ...generated_config_create_deployment_sync.py | 61 - ...enerated_config_delete_deployment_async.py | 56 - ...generated_config_delete_deployment_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 - ..._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 - ..._v1_generated_config_get_resource_async.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 - ...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 - ...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 - ..._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 | 3414 ---- .../v1/scripts/fixup_config_v1_keywords.py | 196 - .../google-cloud-config/v1/setup.py | 91 - .../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.7.txt | 10 - .../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 | 14019 ---------------- .../google/cloud/config/__init__.py | 22 + .../google/cloud/config/gapic_version.py | 2 +- .../google/cloud/config_v1/__init__.py | 22 + .../cloud/config_v1/gapic_metadata.json | 75 + .../google/cloud/config_v1/gapic_version.py | 2 +- .../config_v1/services/config/async_client.py | 550 + .../cloud/config_v1/services/config/client.py | 571 + .../cloud/config_v1/services/config/pagers.py | 128 + .../services/config/transports/base.py | 72 + .../services/config/transports/grpc.py | 131 + .../config/transports/grpc_asyncio.py | 134 + .../services/config/transports/rest.py | 657 +- .../google/cloud/config_v1/types/__init__.py | 22 + .../google/cloud/config_v1/types/config.py | 645 + ...1_generated_config_create_preview_async.py | 0 ...v1_generated_config_create_preview_sync.py | 0 ...1_generated_config_delete_preview_async.py | 0 ...v1_generated_config_delete_preview_sync.py | 0 ...ated_config_export_preview_result_async.py | 0 ...rated_config_export_preview_result_sync.py | 0 ...g_v1_generated_config_get_preview_async.py | 0 ...ig_v1_generated_config_get_preview_sync.py | 0 ...v1_generated_config_list_previews_async.py | 0 ..._v1_generated_config_list_previews_sync.py | 0 ...ippet_metadata_google.cloud.config.v1.json | 1063 +- .../scripts/fixup_config_v1_keywords.py | 5 + .../tests/unit/gapic/config_v1/test_config.py | 5870 +++++-- 104 files changed, 8333 insertions(+), 38069 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/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/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/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/__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/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_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_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_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_resource_async.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_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_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_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.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 rename {owl-bot-staging/google-cloud-config/v1 => packages/google-cloud-config}/samples/generated_samples/config_v1_generated_config_create_preview_async.py (100%) rename {owl-bot-staging/google-cloud-config/v1 => packages/google-cloud-config}/samples/generated_samples/config_v1_generated_config_create_preview_sync.py (100%) rename {owl-bot-staging/google-cloud-config/v1 => packages/google-cloud-config}/samples/generated_samples/config_v1_generated_config_delete_preview_async.py (100%) rename {owl-bot-staging/google-cloud-config/v1 => packages/google-cloud-config}/samples/generated_samples/config_v1_generated_config_delete_preview_sync.py (100%) rename {owl-bot-staging/google-cloud-config/v1 => packages/google-cloud-config}/samples/generated_samples/config_v1_generated_config_export_preview_result_async.py (100%) rename {owl-bot-staging/google-cloud-config/v1 => packages/google-cloud-config}/samples/generated_samples/config_v1_generated_config_export_preview_result_sync.py (100%) rename {owl-bot-staging/google-cloud-config/v1 => packages/google-cloud-config}/samples/generated_samples/config_v1_generated_config_get_preview_async.py (100%) rename {owl-bot-staging/google-cloud-config/v1 => packages/google-cloud-config}/samples/generated_samples/config_v1_generated_config_get_preview_sync.py (100%) rename {owl-bot-staging/google-cloud-config/v1 => packages/google-cloud-config}/samples/generated_samples/config_v1_generated_config_list_previews_async.py (100%) rename {owl-bot-staging/google-cloud-config/v1 => packages/google-cloud-config}/samples/generated_samples/config_v1_generated_config_list_previews_sync.py (100%) 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 29227d4cf419..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/.flake8 +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Generated by synthtool. DO NOT EDIT! -[flake8] -ignore = E203, E266, E501, W503 -exclude = - # Exclude generated code. - **/proto/** - **/gapic/** - **/services/** - **/types/** - *_pb2.py - - # Standard linting exemptions. - **/.nox/** - __pycache__, - .git, - *.pyc, - conf.py 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 7aa890629865..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/cloud/config *.py -recursive-include google/cloud/config_v1 *.py 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 9b1293c47a76..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/README.rst +++ /dev/null @@ -1,49 +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 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 06423be0b592..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/docs/_static/custom.css +++ /dev/null @@ -1,3 +0,0 @@ -dl.field-list > dt { - min-width: 100px -} 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 9da1ab185d60..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/docs/conf.py +++ /dev/null @@ -1,376 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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("..")) - -__version__ = "0.1.0" - -# -- General configuration ------------------------------------------------ - -# If your documentation needs a minimal Sphinx version, state it here. -needs_sphinx = "4.0.1" - -# 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.napoleon", - "sphinx.ext.todo", - "sphinx.ext.viewcode", -] - -# autodoc/autosummary flags -autoclass_content = "both" -autodoc_default_flags = ["members"] -autosummary_generate = True - - -# Add any paths that contain templates here, relative to this directory. -templates_path = ["_templates"] - -# Allow markdown includes (so releases.md can include CHANGLEOG.md) -# http://www.sphinx-doc.org/en/master/markdown.html -source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} - -# The suffix(es) of source filenames. -# You can specify multiple suffix as a list of string: -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"2023, Google, LLC" -author = u"Google APIs" # TODO: autogenerate this bit - -# 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 = 'en' - -# 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"] - -# 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 Python", - "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", - u"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", - u"google-cloud-config Documentation", - author, - "google-cloud-config", - "GAPIC library for Google Cloud Config API", - "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": ("http://python.readthedocs.org/en/latest/", None), - "gax": ("https://gax-python.readthedocs.org/en/latest/", None), - "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), - "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), - "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), - "grpc": ("https://grpc.io/grpc/python/", None), - "requests": ("http://requests.kennethreitz.org/en/stable/", None), - "proto": ("https://proto-plus-python.readthedocs.io/en/stable", 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 91d7ab9a2e0c..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - config_v1/services - config_v1/types 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 cebce4ca0bd1..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/google/cloud/config/__init__.py +++ /dev/null @@ -1,117 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 GetResourceRequest -from google.cloud.config_v1.types.config import GetRevisionRequest -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 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 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 Resource -from google.cloud.config_v1.types.config import ResourceCAIInfo -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 UnlockDeploymentRequest -from google.cloud.config_v1.types.config import UpdateDeploymentRequest - -__all__ = ('ConfigClient', - 'ConfigAsyncClient', - 'ApplyResults', - 'CreateDeploymentRequest', - 'CreatePreviewRequest', - 'DeleteDeploymentRequest', - 'DeletePreviewRequest', - 'DeleteStatefileRequest', - 'Deployment', - 'DeploymentOperationMetadata', - 'ExportDeploymentStatefileRequest', - 'ExportLockInfoRequest', - 'ExportPreviewResultRequest', - 'ExportPreviewResultResponse', - 'ExportRevisionStatefileRequest', - 'GetDeploymentRequest', - 'GetPreviewRequest', - 'GetResourceRequest', - 'GetRevisionRequest', - 'GitSource', - 'ImportStatefileRequest', - 'ListDeploymentsRequest', - 'ListDeploymentsResponse', - 'ListPreviewsRequest', - 'ListPreviewsResponse', - 'ListResourcesRequest', - 'ListResourcesResponse', - 'ListRevisionsRequest', - 'ListRevisionsResponse', - 'LockDeploymentRequest', - 'LockInfo', - 'OperationMetadata', - 'Preview', - 'PreviewArtifacts', - 'PreviewOperationMetadata', - 'PreviewResult', - 'Resource', - 'ResourceCAIInfo', - 'ResourceTerraformInfo', - 'Revision', - 'Statefile', - 'TerraformBlueprint', - 'TerraformError', - 'TerraformOutput', - 'TerraformVariable', - 'UnlockDeploymentRequest', - 'UpdateDeploymentRequest', -) 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 360a0d13ebdd..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 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 cd5c1e43912e..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/__init__.py +++ /dev/null @@ -1,118 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 GetResourceRequest -from .types.config import GetRevisionRequest -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 ListResourcesRequest -from .types.config import ListResourcesResponse -from .types.config import ListRevisionsRequest -from .types.config import ListRevisionsResponse -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 Resource -from .types.config import ResourceCAIInfo -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 UnlockDeploymentRequest -from .types.config import UpdateDeploymentRequest - -__all__ = ( - 'ConfigAsyncClient', -'ApplyResults', -'ConfigClient', -'CreateDeploymentRequest', -'CreatePreviewRequest', -'DeleteDeploymentRequest', -'DeletePreviewRequest', -'DeleteStatefileRequest', -'Deployment', -'DeploymentOperationMetadata', -'ExportDeploymentStatefileRequest', -'ExportLockInfoRequest', -'ExportPreviewResultRequest', -'ExportPreviewResultResponse', -'ExportRevisionStatefileRequest', -'GetDeploymentRequest', -'GetPreviewRequest', -'GetResourceRequest', -'GetRevisionRequest', -'GitSource', -'ImportStatefileRequest', -'ListDeploymentsRequest', -'ListDeploymentsResponse', -'ListPreviewsRequest', -'ListPreviewsResponse', -'ListResourcesRequest', -'ListResourcesResponse', -'ListRevisionsRequest', -'ListRevisionsResponse', -'LockDeploymentRequest', -'LockInfo', -'OperationMetadata', -'Preview', -'PreviewArtifacts', -'PreviewOperationMetadata', -'PreviewResult', -'Resource', -'ResourceCAIInfo', -'ResourceTerraformInfo', -'Revision', -'Statefile', -'TerraformBlueprint', -'TerraformError', -'TerraformOutput', -'TerraformVariable', -'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 190bb0825b1c..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/gapic_metadata.json +++ /dev/null @@ -1,343 +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" - ] - }, - "GetRevision": { - "methods": [ - "get_revision" - ] - }, - "ImportStatefile": { - "methods": [ - "import_statefile" - ] - }, - "ListDeployments": { - "methods": [ - "list_deployments" - ] - }, - "ListPreviews": { - "methods": [ - "list_previews" - ] - }, - "ListResources": { - "methods": [ - "list_resources" - ] - }, - "ListRevisions": { - "methods": [ - "list_revisions" - ] - }, - "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" - ] - }, - "GetRevision": { - "methods": [ - "get_revision" - ] - }, - "ImportStatefile": { - "methods": [ - "import_statefile" - ] - }, - "ListDeployments": { - "methods": [ - "list_deployments" - ] - }, - "ListPreviews": { - "methods": [ - "list_previews" - ] - }, - "ListResources": { - "methods": [ - "list_resources" - ] - }, - "ListRevisions": { - "methods": [ - "list_revisions" - ] - }, - "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" - ] - }, - "GetRevision": { - "methods": [ - "get_revision" - ] - }, - "ImportStatefile": { - "methods": [ - "import_statefile" - ] - }, - "ListDeployments": { - "methods": [ - "list_deployments" - ] - }, - "ListPreviews": { - "methods": [ - "list_previews" - ] - }, - "ListResources": { - "methods": [ - "list_resources" - ] - }, - "ListRevisions": { - "methods": [ - "list_revisions" - ] - }, - "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 360a0d13ebdd..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 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 89a37dc92c5a..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 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 a4e7fa857980..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 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 233fc14ac689..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/async_client.py +++ /dev/null @@ -1,3119 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 -import functools -import re -from typing import Dict, 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 - -try: - OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.AsyncRetry, object] # 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 - - -class ConfigAsyncClient: - """Infrastructure Manager is a managed service that automates - the deployment and management of Google Cloud infrastructure - resources. - """ - - _client: ConfigClient - - DEFAULT_ENDPOINT = ConfigClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = ConfigClient.DEFAULT_MTLS_ENDPOINT - - 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) - 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) - 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 - - get_transport_class = functools.partial(type(ConfigClient).get_transport_class, type(ConfigClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, ConfigTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = 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 (Union[str, ~.ConfigTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "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). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS 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. - - 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, - - ) - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - 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 = gapic_v1.method_async.wrap_method( - self._client._transport.list_deployments, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # 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), - )), - ) - - # 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, - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - 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 = gapic_v1.method_async.wrap_method( - self._client._transport.get_deployment, - default_timeout=None, - client_info=DEFAULT_CLIENT_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), - )), - ) - - # 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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. - has_flattened_params = any([parent, deployment, deployment_id]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - 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 = gapic_v1.method_async.wrap_method( - self._client._transport.create_deployment, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # 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), - )), - ) - - # 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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. - has_flattened_params = any([deployment, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - 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 = gapic_v1.method_async.wrap_method( - self._client._transport.update_deployment, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # 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), - )), - ) - - # 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - 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 = gapic_v1.method_async.wrap_method( - self._client._transport.delete_deployment, - default_timeout=None, - client_info=DEFAULT_CLIENT_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), - )), - ) - - # 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - 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 = gapic_v1.method_async.wrap_method( - self._client._transport.list_revisions, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # 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), - )), - ) - - # 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, - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - 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 = gapic_v1.method_async.wrap_method( - self._client._transport.get_revision, - default_timeout=None, - client_info=DEFAULT_CLIENT_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), - )), - ) - - # 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - 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 = gapic_v1.method_async.wrap_method( - self._client._transport.get_resource, - default_timeout=None, - client_info=DEFAULT_CLIENT_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), - )), - ) - - # 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, str]] = (), - ) -> pagers.ListResourcesAsyncPager: - r"""Lists [Resource][google.cloud.config.v1.Resource]s 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, str]]): Strings which should be - sent along with the request as metadata. - - 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. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - 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 = gapic_v1.method_async.wrap_method( - self._client._transport.list_resources, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # 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), - )), - ) - - # 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, - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.config_v1.types.Statefile: - Contains info about a Terraform state - file - - """ - # Create or coerce a protobuf request object. - request = config.ExportDeploymentStatefileRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.export_deployment_statefile, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # 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), - )), - ) - - # 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.config_v1.types.Statefile: - Contains info about a Terraform state - file - - """ - # Create or coerce a protobuf request object. - request = config.ExportRevisionStatefileRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.export_revision_statefile, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # 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), - )), - ) - - # 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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. - has_flattened_params = any([parent, lock_id]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - 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 = gapic_v1.method_async.wrap_method( - self._client._transport.import_statefile, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # 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), - )), - ) - - # 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - 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 = gapic_v1.method_async.wrap_method( - self._client._transport.delete_statefile, - default_timeout=None, - client_info=DEFAULT_CLIENT_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), - )), - ) - - # 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - 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 = gapic_v1.method_async.wrap_method( - self._client._transport.lock_deployment, - default_timeout=None, - client_info=DEFAULT_CLIENT_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), - )), - ) - - # 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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. - has_flattened_params = any([name, lock_id]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - 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 = gapic_v1.method_async.wrap_method( - self._client._transport.unlock_deployment, - default_timeout=None, - client_info=DEFAULT_CLIENT_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), - )), - ) - - # 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - 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 = gapic_v1.method_async.wrap_method( - self._client._transport.export_lock_info, - default_timeout=None, - client_info=DEFAULT_CLIENT_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), - )), - ) - - # 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, str]] = (), - ) -> 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" - - 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, str]]): Strings which should be - sent along with the request as metadata. - - 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. - has_flattened_params = any([parent, preview]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - 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 = gapic_v1.method_async.wrap_method( - self._client._transport.create_preview, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # 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), - )), - ) - - # 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - 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 = gapic_v1.method_async.wrap_method( - self._client._transport.get_preview, - default_timeout=None, - client_info=DEFAULT_CLIENT_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), - )), - ) - - # 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - 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 = gapic_v1.method_async.wrap_method( - self._client._transport.list_previews, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # 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), - )), - ) - - # 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, - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - 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 = gapic_v1.method_async.wrap_method( - self._client._transport.delete_preview, - default_timeout=None, - client_info=DEFAULT_CLIENT_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), - )), - ) - - # 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.config_v1.types.ExportPreviewResultResponse: - A response to ExportPreviewResult call. Contains preview - results. - - """ - # Create or coerce a protobuf request object. - request = config.ExportPreviewResultRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.export_preview_result, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # 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), - )), - ) - - # 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - 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 = gapic_v1.method_async.wrap_method( - self._client._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_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),)), - ) - - # 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - 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 = gapic_v1.method_async.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_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),)), - ) - - # 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - 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 = gapic_v1.method_async.wrap_method( - self._client._transport.delete_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_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),)), - ) - - # 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - 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 = gapic_v1.method_async.wrap_method( - self._client._transport.cancel_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_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),)), - ) - - # 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - 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 = gapic_v1.method_async.wrap_method( - self._client._transport.set_iam_policy, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # 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),)), - ) - - # 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - 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 = gapic_v1.method_async.wrap_method( - self._client._transport.get_iam_policy, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # 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),)), - ) - - # 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - 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 = gapic_v1.method_async.wrap_method( - self._client._transport.test_iam_permissions, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # 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),)), - ) - - # 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - 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 = gapic_v1.method_async.wrap_method( - self._client._transport.get_location, - default_timeout=None, - client_info=DEFAULT_CLIENT_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),)), - ) - - # 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - 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 = gapic_v1.method_async.wrap_method( - self._client._transport.list_locations, - default_timeout=None, - client_info=DEFAULT_CLIENT_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),)), - ) - - # 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__) - - -__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 807add264d43..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/client.py +++ /dev/null @@ -1,3366 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 -import os -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast - -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 - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # 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 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") - - DEFAULT_ENDPOINT = "config.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @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 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 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): - """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. - """ - 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 - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, 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 (Union[str, ConfigTransport]): The - transport to use. 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. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "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). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS 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. - 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. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - client_options = cast(client_options_lib.ClientOptions, client_options) - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(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. - if isinstance(transport, ConfigTransport): - # transport is a ConfigTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - 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 = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a config.ListDeploymentsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # 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, - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a config.GetDeploymentRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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. - has_flattened_params = any([parent, deployment, deployment_id]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a config.CreateDeploymentRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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. - has_flattened_params = any([deployment, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a config.UpdateDeploymentRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a config.DeleteDeploymentRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a config.ListRevisionsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # 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, - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a config.GetRevisionRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a config.GetResourceRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # 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, str]] = (), - ) -> pagers.ListResourcesPager: - r"""Lists [Resource][google.cloud.config.v1.Resource]s 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, str]]): Strings which should be - sent along with the request as metadata. - - 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. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a config.ListResourcesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # 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, - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.config_v1.types.Statefile: - Contains info about a Terraform state - file - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a config.ExportDeploymentStatefileRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.config_v1.types.Statefile: - Contains info about a Terraform state - file - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a config.ExportRevisionStatefileRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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. - has_flattened_params = any([parent, lock_id]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a config.ImportStatefileRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a config.DeleteStatefileRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a config.LockDeploymentRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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. - has_flattened_params = any([name, lock_id]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a config.UnlockDeploymentRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a config.ExportLockInfoRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # 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, str]] = (), - ) -> 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" - - 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, str]]): Strings which should be - sent along with the request as metadata. - - 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. - has_flattened_params = any([parent, preview]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a config.CreatePreviewRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a config.GetPreviewRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a config.ListPreviewsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # 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, - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a config.DeletePreviewRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.config_v1.types.ExportPreviewResultResponse: - A response to ExportPreviewResult call. Contains preview - results. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a config.ExportPreviewResultRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - 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 = gapic_v1.method.wrap_method( - self._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_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),)), - ) - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - 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 = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_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),)), - ) - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - 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 = gapic_v1.method.wrap_method( - self._transport.delete_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_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),)), - ) - - # 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - 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 = gapic_v1.method.wrap_method( - self._transport.cancel_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_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),)), - ) - - # 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - 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 = gapic_v1.method.wrap_method( - self._transport.set_iam_policy, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # 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),)), - ) - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - 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 = gapic_v1.method.wrap_method( - self._transport.get_iam_policy, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # 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),)), - ) - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def test_iam_permissions( - self, - request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - 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 = gapic_v1.method.wrap_method( - self._transport.test_iam_permissions, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # 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),)), - ) - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - 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 = gapic_v1.method.wrap_method( - self._transport.get_location, - default_timeout=None, - client_info=DEFAULT_CLIENT_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),)), - ) - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - 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, str]] = (), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - 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 = gapic_v1.method.wrap_method( - self._transport.list_locations, - default_timeout=None, - client_info=DEFAULT_CLIENT_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),)), - ) - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__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 817c71ba5592..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/pagers.py +++ /dev/null @@ -1,502 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -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, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = config.ListDeploymentsRequest(request) - self._response = response - 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, 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, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = config.ListDeploymentsRequest(request) - self._response = response - 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, 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, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = config.ListRevisionsRequest(request) - self._response = response - 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, 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, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = config.ListRevisionsRequest(request) - self._response = response - 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, 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, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = config.ListResourcesRequest(request) - self._response = response - 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, 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, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = config.ListResourcesRequest(request) - self._response = response - 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, 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, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = config.ListPreviewsRequest(request) - self._response = response - 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, 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, - *, - metadata: Sequence[Tuple[str, str]] = ()): - """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. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = config.ListPreviewsRequest(request) - self._response = response - 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, 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) 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 30139049a722..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 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 13f602b43833..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/transports/base.py +++ /dev/null @@ -1,521 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 - -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__) - - -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. - 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 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: - 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 - - 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, - ), - } - - 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_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 93dcf49a8429..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/transports/grpc.py +++ /dev/null @@ -1,1005 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 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 - -import grpc # 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 - - -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[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. - 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 ``channel`` 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 ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - 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 ``channel`` 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 ``channel`` 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 channel: - # Ignore credentials if a channel was passed. - credentials = False - # 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: - self._grpc_channel = type(self).create_channel( - 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), - ], - ) - - # Wrap messages. This must be done after self._grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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 [Resource][google.cloud.config.v1.Resource]s 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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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'] - - def close(self): - self.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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 946d198514de..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/transports/grpc_asyncio.py +++ /dev/null @@ -1,1004 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 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 operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # 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 - - -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`. - This argument is ignored if ``channel`` 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`. - 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[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. - 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 ``channel`` 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 ``channel`` 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[aio.Channel]): A ``Channel`` instance through - which to make calls. - 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 ``channel`` 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 ``channel`` 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 channel: - # Ignore credentials if a channel was passed. - credentials = False - # 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: - self._grpc_channel = type(self).create_channel( - 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), - ], - ) - - # Wrap messages. This must be done after self._grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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 [Resource][google.cloud.config.v1.Resource]s 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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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'] - - def close(self): - return self.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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 a1a4f1801c92..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/services/config/transports/rest.py +++ /dev/null @@ -1,3431 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # 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 path_template -from google.api_core import gapic_v1 - -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 -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - - -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 .base import ConfigTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=requests_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_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_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_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_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, str]]) -> Tuple[config.CreateDeploymentRequest, Sequence[Tuple[str, str]]]: - """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 - - 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_create_preview(self, request: config.CreatePreviewRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[config.CreatePreviewRequest, Sequence[Tuple[str, str]]]: - """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 - - 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_deployment(self, request: config.DeleteDeploymentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[config.DeleteDeploymentRequest, Sequence[Tuple[str, str]]]: - """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 - - 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_preview(self, request: config.DeletePreviewRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[config.DeletePreviewRequest, Sequence[Tuple[str, str]]]: - """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 - - 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_statefile(self, request: config.DeleteStatefileRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[config.DeleteStatefileRequest, Sequence[Tuple[str, str]]]: - """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, str]]) -> Tuple[config.ExportDeploymentStatefileRequest, Sequence[Tuple[str, str]]]: - """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 - - 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_export_lock_info(self, request: config.ExportLockInfoRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[config.ExportLockInfoRequest, Sequence[Tuple[str, str]]]: - """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 - - 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_export_preview_result(self, request: config.ExportPreviewResultRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[config.ExportPreviewResultRequest, Sequence[Tuple[str, str]]]: - """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 - - 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_export_revision_statefile(self, request: config.ExportRevisionStatefileRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[config.ExportRevisionStatefileRequest, Sequence[Tuple[str, str]]]: - """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 - - 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_deployment(self, request: config.GetDeploymentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[config.GetDeploymentRequest, Sequence[Tuple[str, str]]]: - """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 - - 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_preview(self, request: config.GetPreviewRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[config.GetPreviewRequest, Sequence[Tuple[str, str]]]: - """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 - - 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_resource(self, request: config.GetResourceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[config.GetResourceRequest, Sequence[Tuple[str, str]]]: - """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 - - 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_revision(self, request: config.GetRevisionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[config.GetRevisionRequest, Sequence[Tuple[str, str]]]: - """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 - - 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_import_statefile(self, request: config.ImportStatefileRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[config.ImportStatefileRequest, Sequence[Tuple[str, str]]]: - """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 - - 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_deployments(self, request: config.ListDeploymentsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[config.ListDeploymentsRequest, Sequence[Tuple[str, str]]]: - """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 - - 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_previews(self, request: config.ListPreviewsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[config.ListPreviewsRequest, Sequence[Tuple[str, str]]]: - """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 - - 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_resources(self, request: config.ListResourcesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[config.ListResourcesRequest, Sequence[Tuple[str, str]]]: - """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 - - 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_revisions(self, request: config.ListRevisionsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[config.ListRevisionsRequest, Sequence[Tuple[str, str]]]: - """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 - - 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_lock_deployment(self, request: config.LockDeploymentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[config.LockDeploymentRequest, Sequence[Tuple[str, str]]]: - """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 - - 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_unlock_deployment(self, request: config.UnlockDeploymentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[config.UnlockDeploymentRequest, Sequence[Tuple[str, str]]]: - """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 - - 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_update_deployment(self, request: config.UpdateDeploymentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[config.UpdateDeploymentRequest, Sequence[Tuple[str, str]]]: - """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 - - 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_location( - self, request: locations_pb2.GetLocationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[locations_pb2.GetLocationRequest, Sequence[Tuple[str, str]]]: - """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, str]] - ) -> Tuple[locations_pb2.ListLocationsRequest, Sequence[Tuple[str, str]]]: - """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, str]] - ) -> Tuple[iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, str]]]: - """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, str]] - ) -> Tuple[iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, str]]]: - """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, str]] - ) -> Tuple[iam_policy_pb2.TestIamPermissionsRequest, Sequence[Tuple[str, str]]]: - """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, str]] - ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, str]]]: - """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, str]] - ) -> Tuple[operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, str]]]: - """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, str]] - ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: - """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, str]] - ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: - """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(ConfigTransport): - """REST 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 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. - 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 - 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 - ) - 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(ConfigRestStub): - def __hash__(self): - return hash("CreateDeployment") - - __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} - - def __call__(self, - request: config.CreateDeploymentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/locations/*}/deployments', - 'body': 'deployment', - }, - ] - request, metadata = self._interceptor.pre_create_deployment(request, metadata) - pb_request = config.CreateDeploymentRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=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) - return resp - - class _CreatePreview(ConfigRestStub): - def __hash__(self): - return hash("CreatePreview") - - __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} - - def __call__(self, - request: config.CreatePreviewRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/locations/*}/previews', - 'body': 'preview', - }, - ] - request, metadata = self._interceptor.pre_create_preview(request, metadata) - pb_request = config.CreatePreviewRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=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) - return resp - - class _DeleteDeployment(ConfigRestStub): - def __hash__(self): - return hash("DeleteDeployment") - - __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} - - def __call__(self, - request: config.DeleteDeploymentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/deployments/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_deployment(request, metadata) - pb_request = config.DeleteDeploymentRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # 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) - return resp - - class _DeletePreview(ConfigRestStub): - def __hash__(self): - return hash("DeletePreview") - - __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} - - def __call__(self, - request: config.DeletePreviewRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/previews/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_preview(request, metadata) - pb_request = config.DeletePreviewRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # 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) - return resp - - class _DeleteStatefile(ConfigRestStub): - def __hash__(self): - return hash("DeleteStatefile") - - __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} - - def __call__(self, - request: config.DeleteStatefileRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{name=projects/*/locations/*/deployments/*}:deleteState', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_delete_statefile(request, metadata) - pb_request = config.DeleteStatefileRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=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(ConfigRestStub): - def __hash__(self): - return hash("ExportDeploymentStatefile") - - __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} - - def __call__(self, - request: config.ExportDeploymentStatefileRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.config.Statefile: - Contains info about a Terraform state - file - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/locations/*/deployments/*}:exportState', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_export_deployment_statefile(request, metadata) - pb_request = config.ExportDeploymentStatefileRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=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) - return resp - - class _ExportLockInfo(ConfigRestStub): - def __hash__(self): - return hash("ExportLockInfo") - - __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} - - def __call__(self, - request: config.ExportLockInfoRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.config.LockInfo: - Details about the lock which locked - the deployment. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/deployments/*}:exportLock', - }, - ] - request, metadata = self._interceptor.pre_export_lock_info(request, metadata) - pb_request = config.ExportLockInfoRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # 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) - return resp - - class _ExportPreviewResult(ConfigRestStub): - def __hash__(self): - return hash("ExportPreviewResult") - - __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} - - def __call__(self, - request: config.ExportPreviewResultRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.config.ExportPreviewResultResponse: - A response to ``ExportPreviewResult`` call. Contains - preview results. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/locations/*/previews/*}:export', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_export_preview_result(request, metadata) - pb_request = config.ExportPreviewResultRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=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) - return resp - - class _ExportRevisionStatefile(ConfigRestStub): - def __hash__(self): - return hash("ExportRevisionStatefile") - - __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} - - def __call__(self, - request: config.ExportRevisionStatefileRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.config.Statefile: - Contains info about a Terraform state - file - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/locations/*/deployments/*/revisions/*}:exportState', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_export_revision_statefile(request, metadata) - pb_request = config.ExportRevisionStatefileRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=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) - return resp - - class _GetDeployment(ConfigRestStub): - def __hash__(self): - return hash("GetDeployment") - - __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} - - def __call__(self, - request: config.GetDeploymentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.config.Deployment: - A Deployment is a group of resources - and configs managed and provisioned by - Infra Manager. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/deployments/*}', - }, - ] - request, metadata = self._interceptor.pre_get_deployment(request, metadata) - pb_request = config.GetDeploymentRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # 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) - return resp - - class _GetPreview(ConfigRestStub): - def __hash__(self): - return hash("GetPreview") - - __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} - - def __call__(self, - request: config.GetPreviewRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/previews/*}', - }, - ] - request, metadata = self._interceptor.pre_get_preview(request, metadata) - pb_request = config.GetPreviewRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # 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) - return resp - - class _GetResource(ConfigRestStub): - def __hash__(self): - return hash("GetResource") - - __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} - - def __call__(self, - request: config.GetResourceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.config.Resource: - Resource represents a Google Cloud - Platform resource actuated by IM. - Resources are child resources of - Revisions. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/deployments/*/revisions/*/resources/*}', - }, - ] - request, metadata = self._interceptor.pre_get_resource(request, metadata) - pb_request = config.GetResourceRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # 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) - return resp - - class _GetRevision(ConfigRestStub): - def __hash__(self): - return hash("GetRevision") - - __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} - - def __call__(self, - request: config.GetRevisionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - 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: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/deployments/*/revisions/*}', - }, - ] - request, metadata = self._interceptor.pre_get_revision(request, metadata) - pb_request = config.GetRevisionRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # 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) - return resp - - class _ImportStatefile(ConfigRestStub): - def __hash__(self): - return hash("ImportStatefile") - - __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} - - def __call__(self, - request: config.ImportStatefileRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.config.Statefile: - Contains info about a Terraform state - file - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/locations/*/deployments/*}:importState', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_import_statefile(request, metadata) - pb_request = config.ImportStatefileRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=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) - return resp - - class _ListDeployments(ConfigRestStub): - def __hash__(self): - return hash("ListDeployments") - - __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} - - def __call__(self, - request: config.ListDeploymentsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.config.ListDeploymentsResponse: - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/locations/*}/deployments', - }, - ] - request, metadata = self._interceptor.pre_list_deployments(request, metadata) - pb_request = config.ListDeploymentsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # 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) - return resp - - class _ListPreviews(ConfigRestStub): - def __hash__(self): - return hash("ListPreviews") - - __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} - - def __call__(self, - request: config.ListPreviewsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.config.ListPreviewsResponse: - A response to a ``ListPreviews`` call. Contains a list - of Previews. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/locations/*}/previews', - }, - ] - request, metadata = self._interceptor.pre_list_previews(request, metadata) - pb_request = config.ListPreviewsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # 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) - return resp - - class _ListResources(ConfigRestStub): - def __hash__(self): - return hash("ListResources") - - __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} - - def __call__(self, - request: config.ListResourcesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.config.ListResourcesResponse: - A response to a 'ListResources' call. - Contains a list of Resources. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/locations/*/deployments/*/revisions/*}/resources', - }, - ] - request, metadata = self._interceptor.pre_list_resources(request, metadata) - pb_request = config.ListResourcesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # 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) - return resp - - class _ListRevisions(ConfigRestStub): - def __hash__(self): - return hash("ListRevisions") - - __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} - - def __call__(self, - request: config.ListRevisionsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.config.ListRevisionsResponse: - A response to a 'ListRevisions' call. - Contains a list of Revisions. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/locations/*/deployments/*}/revisions', - }, - ] - request, metadata = self._interceptor.pre_list_revisions(request, metadata) - pb_request = config.ListRevisionsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # 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) - return resp - - class _LockDeployment(ConfigRestStub): - def __hash__(self): - return hash("LockDeployment") - - __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} - - def __call__(self, - request: config.LockDeploymentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{name=projects/*/locations/*/deployments/*}:lock', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_lock_deployment(request, metadata) - pb_request = config.LockDeploymentRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=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) - return resp - - class _UnlockDeployment(ConfigRestStub): - def __hash__(self): - return hash("UnlockDeployment") - - __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} - - def __call__(self, - request: config.UnlockDeploymentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{name=projects/*/locations/*/deployments/*}:unlock', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_unlock_deployment(request, metadata) - pb_request = config.UnlockDeploymentRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=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) - return resp - - class _UpdateDeployment(ConfigRestStub): - def __hash__(self): - return hash("UpdateDeployment") - - __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} - - def __call__(self, - request: config.UpdateDeploymentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1/{deployment.name=projects/*/locations/*/deployments/*}', - 'body': 'deployment', - }, - ] - request, metadata = self._interceptor.pre_update_deployment(request, metadata) - pb_request = config.UpdateDeploymentRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=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) - 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_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 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_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 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(ConfigRestStub): - def __call__(self, - request: locations_pb2.GetLocationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - locations_pb2.Location: Response from GetLocation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_location(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = locations_pb2.Location() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_location(resp) - return resp - - @property - def list_locations(self): - return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore - - class _ListLocations(ConfigRestStub): - def __call__(self, - request: locations_pb2.ListLocationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - locations_pb2.ListLocationsResponse: Response from ListLocations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*}/locations', - }, - ] - - request, metadata = self._interceptor.pre_list_locations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = locations_pb2.ListLocationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_locations(resp) - return resp - - @property - def get_iam_policy(self): - return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore - - class _GetIamPolicy(ConfigRestStub): - def __call__(self, - request: iam_policy_pb2.GetIamPolicyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - policy_pb2.Policy: Response from GetIamPolicy method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{resource=projects/*/locations/*/deployments/*}:getIamPolicy', - }, - ] - - request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = policy_pb2.Policy() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_iam_policy(resp) - return resp - - @property - def set_iam_policy(self): - return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore - - class _SetIamPolicy(ConfigRestStub): - def __call__(self, - request: iam_policy_pb2.SetIamPolicyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - policy_pb2.Policy: Response from SetIamPolicy method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/deployments/*}:setIamPolicy', - 'body': '*', - }, - ] - - request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - body = json.dumps(transcoded_request['body']) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - data=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) - - resp = policy_pb2.Policy() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_set_iam_policy(resp) - return resp - - @property - def test_iam_permissions(self): - return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore - - class _TestIamPermissions(ConfigRestStub): - def __call__(self, - request: iam_policy_pb2.TestIamPermissionsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - iam_policy_pb2.TestIamPermissionsResponse: Response from TestIamPermissions method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/deployments/*}:testIamPermissions', - 'body': '*', - }, - ] - - request, metadata = self._interceptor.pre_test_iam_permissions(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - body = json.dumps(transcoded_request['body']) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - data=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) - - resp = iam_policy_pb2.TestIamPermissionsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_test_iam_permissions(resp) - return resp - - @property - def cancel_operation(self): - return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore - - class _CancelOperation(ConfigRestStub): - def __call__(self, - request: operations_pb2.CancelOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}:cancel', - 'body': '*', - }, - ] - - request, metadata = self._interceptor.pre_cancel_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - body = json.dumps(transcoded_request['body']) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - data=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(ConfigRestStub): - def __call__(self, - request: operations_pb2.DeleteOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}', - }, - ] - - request, metadata = self._interceptor.pre_delete_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # 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(ConfigRestStub): - def __call__(self, - request: operations_pb2.GetOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - operations_pb2.Operation: Response from GetOperation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_operation(resp) - return resp - - @property - def list_operations(self): - return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - - class _ListOperations(ConfigRestStub): - def __call__(self, - request: operations_pb2.ListOperationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - operations_pb2.ListOperationsResponse: Response from ListOperations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*}/operations', - }, - ] - - request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_operations(resp) - 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/types/__init__.py b/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/types/__init__.py deleted file mode 100644 index 8c07419e7426..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/types/__init__.py +++ /dev/null @@ -1,110 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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, - GetResourceRequest, - GetRevisionRequest, - GitSource, - ImportStatefileRequest, - ListDeploymentsRequest, - ListDeploymentsResponse, - ListPreviewsRequest, - ListPreviewsResponse, - ListResourcesRequest, - ListResourcesResponse, - ListRevisionsRequest, - ListRevisionsResponse, - LockDeploymentRequest, - LockInfo, - OperationMetadata, - Preview, - PreviewArtifacts, - PreviewOperationMetadata, - PreviewResult, - Resource, - ResourceCAIInfo, - ResourceTerraformInfo, - Revision, - Statefile, - TerraformBlueprint, - TerraformError, - TerraformOutput, - TerraformVariable, - UnlockDeploymentRequest, - UpdateDeploymentRequest, -) - -__all__ = ( - 'ApplyResults', - 'CreateDeploymentRequest', - 'CreatePreviewRequest', - 'DeleteDeploymentRequest', - 'DeletePreviewRequest', - 'DeleteStatefileRequest', - 'Deployment', - 'DeploymentOperationMetadata', - 'ExportDeploymentStatefileRequest', - 'ExportLockInfoRequest', - 'ExportPreviewResultRequest', - 'ExportPreviewResultResponse', - 'ExportRevisionStatefileRequest', - 'GetDeploymentRequest', - 'GetPreviewRequest', - 'GetResourceRequest', - 'GetRevisionRequest', - 'GitSource', - 'ImportStatefileRequest', - 'ListDeploymentsRequest', - 'ListDeploymentsResponse', - 'ListPreviewsRequest', - 'ListPreviewsResponse', - 'ListResourcesRequest', - 'ListResourcesResponse', - 'ListRevisionsRequest', - 'ListRevisionsResponse', - 'LockDeploymentRequest', - 'LockInfo', - 'OperationMetadata', - 'Preview', - 'PreviewArtifacts', - 'PreviewOperationMetadata', - 'PreviewResult', - 'Resource', - 'ResourceCAIInfo', - 'ResourceTerraformInfo', - 'Revision', - 'Statefile', - 'TerraformBlueprint', - 'TerraformError', - 'TerraformOutput', - 'TerraformVariable', - 'UnlockDeploymentRequest', - 'UpdateDeploymentRequest', -) 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 e3ac91093f6b..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/google/cloud/config_v1/types/config.py +++ /dev/null @@ -1,2442 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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={ - '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', - }, -) - - -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): - 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]): - 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): - Optional. 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. - """ - 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, - ) - - -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): - Required. 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): - Required. URI of a public Git repo. - - This field is a member of `oneof`_ ``source``. - input_values (MutableMapping[str, google.cloud.config_v1.types.TerraformVariable]): - 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): - 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 or set to 0, - all resources will be returned. - 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 or set to 0, - all resources will be returned. - 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 [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. - """ - 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. - """ - ERROR_CODE_UNSPECIFIED = 0 - CLOUD_BUILD_PERMISSION_DENIED = 1 - APPLY_BUILD_API_FAILED = 4 - APPLY_BUILD_RUN_FAILED = 5 - - 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, - ) - - -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): - 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 - """ - 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 - - 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 or set to 0, - all resources will be returned. - 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][]s. - 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): - Optional. Optional service account. If - omitted, the deployment resource reference must - be provided, and the service account attached to - the deployment will be used. - 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. - """ - 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, - ) - - -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. - """ - 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 - - 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 or - set to 0, all resources will be returned. - 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][]s. - 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, - ) - - -__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 d57180871112..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/noxfile.py +++ /dev/null @@ -1,177 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 shutil -import subprocess -import sys - - -import nox # type: ignore - -ALL_PYTHON = [ - "3.7", - "3.8", - "3.9", - "3.10", - "3.11", - "3.12" -] - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = 'google-cloud-config' - -BLACK_VERSION = "black==22.3.0" -BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] -DEFAULT_PYTHON_VERSION = "3.12" - -nox.sessions = [ - "unit", - "cover", - "mypy", - "check_lower_bounds" - # exclude update_lower_bounds from default - "docs", - "blacken", - "lint", -] - -@nox.session(python=ALL_PYTHON) -def unit(session): - """Run the unit test suite.""" - - session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') - session.install('-e', '.') - - session.run( - 'py.test', - '--quiet', - '--cov=google/cloud/config_v1/', - '--cov=tests/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(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=ALL_PYTHON) -def mypy(session): - """Run the type checker.""" - session.install( - 'mypy', - '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 docs(session): - """Build the docs for this library.""" - - session.install("-e", ".") - session.install("sphinx==7.0.1", "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", - "-d", - os.path.join("docs", "_build", "doctrees", ""), - os.path.join("docs", ""), - os.path.join("docs", "_build", "html", ""), - ) - - -@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", - *BLACK_PATHS, - ) - session.run("flake8", "google", "tests", "samples") - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def blacken(session): - """Run black. Format code to uniform standard.""" - session.install(BLACK_VERSION) - session.run( - "black", - *BLACK_PATHS, - ) 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 9f5a6f8d4515..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 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 4ff94956cc0b..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 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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_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 866144f716af..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 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 198ecc75583f..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 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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_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 9b29aaeda1cc..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 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 0e0bff321bfd..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 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 9ddc0b71e08b..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 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 de50f1469e96..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 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 618eccf6031e..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 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 9dc042354cbb..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 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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_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 cb5c02d7d650..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 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 c101b8f3554f..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 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 12d9da8c4d41..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 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 29877f5621c2..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 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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_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 5af489c3823a..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 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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_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 c010cc9b97b3..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 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 cbbbedb33498..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 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 95ef695541a5..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 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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_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 93d7e21bed32..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 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 4fdbe2b26933..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 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 0e610caebe93..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 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 dac0a9c6e11e..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 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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_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 4ce4fa8fe6fd..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 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 620e9bf97485..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 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 0403d42efd50..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 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 42746c70dd18..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 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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_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 4bad83dff4e0..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 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 d706b4f4fe8c..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 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 f0ec2cf6aa7d..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 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 a0e78638e712..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 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 7d705d83d6b9..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 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 3ae193bf307c..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 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 9f9d26c92521..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/snippet_metadata_google.cloud.config.v1.json +++ /dev/null @@ -1,3414 +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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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": 59, - "start": 27, - "type": "FULL" - }, - { - "end": 59, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 49, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 56, - "start": 50, - "type": "REQUEST_EXECUTION" - }, - { - "end": 60, - "start": 57, - "type": "RESPONSE_HANDLING" - } - ], - "title": "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, str]" - } - ], - "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": 59, - "start": 27, - "type": "FULL" - }, - { - "end": 59, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 49, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 56, - "start": 50, - "type": "REQUEST_EXECUTION" - }, - { - "end": 60, - "start": 57, - "type": "RESPONSE_HANDLING" - } - ], - "title": "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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", - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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.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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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_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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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.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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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, str]" - } - ], - "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 c9978014e855..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/scripts/fixup_config_v1_keywords.py +++ /dev/null @@ -1,196 +0,0 @@ -#! /usr/bin/env python3 -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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_revision': ('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_resources': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), - 'list_revisions': ('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 80cc751f2ff4..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/setup.py +++ /dev/null @@ -1,91 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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.0, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "proto-plus >= 1.22.3, <2.0.0dev", - "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", - "grpc-google-iam-v1 >= 0.12.4, <1.0.0dev", -] -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", - "Operating System :: OS Independent", - "Topic :: Internet", - ], - platforms="Posix; MacOS X; Windows", - packages=packages, - python_requires=">=3.7", - install_requires=dependencies, - 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.7.txt b/owl-bot-staging/google-cloud-config/v1/testing/constraints-3.7.txt deleted file mode 100644 index 44ffd04543a8..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/testing/constraints-3.7.txt +++ /dev/null @@ -1,10 +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.0dev", -# Then this file should have google-cloud-foo==1.14.0 -google-api-core==1.34.0 -proto-plus==1.22.3 -protobuf==3.19.5 -grpc-google-iam-v1==0.12.4 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 1b4db446eb8d..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/tests/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 1b4db446eb8d..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/tests/unit/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 1b4db446eb8d..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 1b4db446eb8d..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 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 bc7c39e1f8c4..000000000000 --- a/owl-bot-staging/google-cloud-config/v1/tests/unit/gapic/config_v1/test_config.py +++ /dev/null @@ -1,14019 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 -from google.protobuf import json_format -import json -import math -import pytest -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 - -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.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 - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# 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 - - -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 - - -@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", modify_default_endpoint(ConfigClient)) -@mock.patch.object(ConfigAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(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, - 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): - client = client_class(transport=transport_name) - - # 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): - client = client_class(transport=transport_name) - - # 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, - 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, - 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", modify_default_endpoint(ConfigClient)) -@mock.patch.object(ConfigAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(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 - 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 - 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, - 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 - - -@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, - 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, - 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, - 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] - assert args[0] == config.ListDeploymentsRequest() - - # 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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_deployments), - '__call__') as call: - client.list_deployments() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == config.ListDeploymentsRequest() - -@pytest.mark.asyncio -async def test_list_deployments_async(transport: str = 'grpc_asyncio', request_type=config.ListDeploymentsRequest): - client = ConfigAsyncClient( - 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 =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] - assert args[0] == config.ListDeploymentsRequest() - - # 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=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 = 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=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.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=ga_credentials.AnonymousCredentials(), - ) - - # 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, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_deployments(request={}) - - assert pager._metadata == metadata - - 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=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__', 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=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__', 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, - ) - 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] - assert args[0] == config.GetDeploymentRequest() - - # 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 - - -def test_get_deployment_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_deployment), - '__call__') as call: - client.get_deployment() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == config.GetDeploymentRequest() - -@pytest.mark.asyncio -async def test_get_deployment_async(transport: str = 'grpc_asyncio', request_type=config.GetDeploymentRequest): - client = ConfigAsyncClient( - 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 =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, - )) - 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] - assert args[0] == config.GetDeploymentRequest() - - # 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 - - -@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=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 = 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=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.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=ga_credentials.AnonymousCredentials(), - ) - - # 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] - assert args[0] == config.CreateDeploymentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_create_deployment_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_deployment), - '__call__') as call: - client.create_deployment() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == config.CreateDeploymentRequest() - -@pytest.mark.asyncio -async def test_create_deployment_async(transport: str = 'grpc_asyncio', request_type=config.CreateDeploymentRequest): - client = ConfigAsyncClient( - 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 = 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] - assert args[0] == config.CreateDeploymentRequest() - - # 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=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 = 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=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.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=ga_credentials.AnonymousCredentials(), - ) - - # 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] - assert args[0] == config.UpdateDeploymentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_update_deployment_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_deployment), - '__call__') as call: - client.update_deployment() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == config.UpdateDeploymentRequest() - -@pytest.mark.asyncio -async def test_update_deployment_async(transport: str = 'grpc_asyncio', request_type=config.UpdateDeploymentRequest): - client = ConfigAsyncClient( - 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 = 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] - assert args[0] == config.UpdateDeploymentRequest() - - # 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=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 = 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=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.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=ga_credentials.AnonymousCredentials(), - ) - - # 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] - assert args[0] == config.DeleteDeploymentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_delete_deployment_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_deployment), - '__call__') as call: - client.delete_deployment() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == config.DeleteDeploymentRequest() - -@pytest.mark.asyncio -async def test_delete_deployment_async(transport: str = 'grpc_asyncio', request_type=config.DeleteDeploymentRequest): - client = ConfigAsyncClient( - 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 = 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] - assert args[0] == config.DeleteDeploymentRequest() - - # 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=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 = 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=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.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=ga_credentials.AnonymousCredentials(), - ) - - # 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] - assert args[0] == config.ListRevisionsRequest() - - # 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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_revisions), - '__call__') as call: - client.list_revisions() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == config.ListRevisionsRequest() - -@pytest.mark.asyncio -async def test_list_revisions_async(transport: str = 'grpc_asyncio', request_type=config.ListRevisionsRequest): - client = ConfigAsyncClient( - 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 =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] - assert args[0] == config.ListRevisionsRequest() - - # 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=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 = 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=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.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=ga_credentials.AnonymousCredentials(), - ) - - # 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, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_revisions(request={}) - - assert pager._metadata == metadata - - 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=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__', 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=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__', 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', - ) - 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] - assert args[0] == config.GetRevisionRequest() - - # 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' - - -def test_get_revision_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_revision), - '__call__') as call: - client.get_revision() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == config.GetRevisionRequest() - -@pytest.mark.asyncio -async def test_get_revision_async(transport: str = 'grpc_asyncio', request_type=config.GetRevisionRequest): - client = ConfigAsyncClient( - 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 =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', - )) - 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] - assert args[0] == config.GetRevisionRequest() - - # 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' - - -@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=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 = 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=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.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=ga_credentials.AnonymousCredentials(), - ) - - # 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] - assert args[0] == config.GetResourceRequest() - - # 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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_resource), - '__call__') as call: - client.get_resource() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == config.GetResourceRequest() - -@pytest.mark.asyncio -async def test_get_resource_async(transport: str = 'grpc_asyncio', request_type=config.GetResourceRequest): - client = ConfigAsyncClient( - 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 =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] - assert args[0] == config.GetResourceRequest() - - # 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=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 = 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=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.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=ga_credentials.AnonymousCredentials(), - ) - - # 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] - assert args[0] == config.ListResourcesRequest() - - # 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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_resources), - '__call__') as call: - client.list_resources() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == config.ListResourcesRequest() - -@pytest.mark.asyncio -async def test_list_resources_async(transport: str = 'grpc_asyncio', request_type=config.ListResourcesRequest): - client = ConfigAsyncClient( - 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 =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] - assert args[0] == config.ListResourcesRequest() - - # 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=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 = 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=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.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=ga_credentials.AnonymousCredentials(), - ) - - # 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, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_resources(request={}) - - assert pager._metadata == metadata - - 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=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__', 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=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__', 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] - assert args[0] == config.ExportDeploymentStatefileRequest() - - # 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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # 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: - client.export_deployment_statefile() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == config.ExportDeploymentStatefileRequest() - -@pytest.mark.asyncio -async def test_export_deployment_statefile_async(transport: str = 'grpc_asyncio', request_type=config.ExportDeploymentStatefileRequest): - client = ConfigAsyncClient( - 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 =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] - assert args[0] == config.ExportDeploymentStatefileRequest() - - # 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=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 = 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] - assert args[0] == config.ExportRevisionStatefileRequest() - - # 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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # 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: - client.export_revision_statefile() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == config.ExportRevisionStatefileRequest() - -@pytest.mark.asyncio -async def test_export_revision_statefile_async(transport: str = 'grpc_asyncio', request_type=config.ExportRevisionStatefileRequest): - client = ConfigAsyncClient( - 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 =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] - assert args[0] == config.ExportRevisionStatefileRequest() - - # 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=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 = 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] - assert args[0] == config.ImportStatefileRequest() - - # 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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_statefile), - '__call__') as call: - client.import_statefile() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == config.ImportStatefileRequest() - -@pytest.mark.asyncio -async def test_import_statefile_async(transport: str = 'grpc_asyncio', request_type=config.ImportStatefileRequest): - client = ConfigAsyncClient( - 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 =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] - assert args[0] == config.ImportStatefileRequest() - - # 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=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 = 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=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.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=ga_credentials.AnonymousCredentials(), - ) - - # 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] - assert args[0] == config.DeleteStatefileRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_statefile_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_statefile), - '__call__') as call: - client.delete_statefile() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == config.DeleteStatefileRequest() - -@pytest.mark.asyncio -async def test_delete_statefile_async(transport: str = 'grpc_asyncio', request_type=config.DeleteStatefileRequest): - client = ConfigAsyncClient( - 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 = 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] - assert args[0] == config.DeleteStatefileRequest() - - # 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=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 = 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=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.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=ga_credentials.AnonymousCredentials(), - ) - - # 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] - assert args[0] == config.LockDeploymentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_lock_deployment_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.lock_deployment), - '__call__') as call: - client.lock_deployment() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == config.LockDeploymentRequest() - -@pytest.mark.asyncio -async def test_lock_deployment_async(transport: str = 'grpc_asyncio', request_type=config.LockDeploymentRequest): - client = ConfigAsyncClient( - 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 = 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] - assert args[0] == config.LockDeploymentRequest() - - # 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=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 = 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=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.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=ga_credentials.AnonymousCredentials(), - ) - - # 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] - assert args[0] == config.UnlockDeploymentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_unlock_deployment_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.unlock_deployment), - '__call__') as call: - client.unlock_deployment() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == config.UnlockDeploymentRequest() - -@pytest.mark.asyncio -async def test_unlock_deployment_async(transport: str = 'grpc_asyncio', request_type=config.UnlockDeploymentRequest): - client = ConfigAsyncClient( - 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 = 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] - assert args[0] == config.UnlockDeploymentRequest() - - # 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=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 = 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=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.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=ga_credentials.AnonymousCredentials(), - ) - - # 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] - assert args[0] == config.ExportLockInfoRequest() - - # 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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # 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: - client.export_lock_info() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == config.ExportLockInfoRequest() - -@pytest.mark.asyncio -async def test_export_lock_info_async(transport: str = 'grpc_asyncio', request_type=config.ExportLockInfoRequest): - client = ConfigAsyncClient( - 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 =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] - assert args[0] == config.ExportLockInfoRequest() - - # 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=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 = 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=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.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=ga_credentials.AnonymousCredentials(), - ) - - # 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] - assert args[0] == config.CreatePreviewRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_create_preview_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_preview), - '__call__') as call: - client.create_preview() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == config.CreatePreviewRequest() - -@pytest.mark.asyncio -async def test_create_preview_async(transport: str = 'grpc_asyncio', request_type=config.CreatePreviewRequest): - client = ConfigAsyncClient( - 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 = 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] - assert args[0] == config.CreatePreviewRequest() - - # 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=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 = 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=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.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=ga_credentials.AnonymousCredentials(), - ) - - # 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', - ) - 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] - assert args[0] == config.GetPreviewRequest() - - # 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' - - -def test_get_preview_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_preview), - '__call__') as call: - client.get_preview() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == config.GetPreviewRequest() - -@pytest.mark.asyncio -async def test_get_preview_async(transport: str = 'grpc_asyncio', request_type=config.GetPreviewRequest): - client = ConfigAsyncClient( - 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 =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', - )) - 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] - assert args[0] == config.GetPreviewRequest() - - # 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' - - -@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=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 = 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=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.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=ga_credentials.AnonymousCredentials(), - ) - - # 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] - assert args[0] == config.ListPreviewsRequest() - - # 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_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_previews), - '__call__') as call: - client.list_previews() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == config.ListPreviewsRequest() - -@pytest.mark.asyncio -async def test_list_previews_async(transport: str = 'grpc_asyncio', request_type=config.ListPreviewsRequest): - client = ConfigAsyncClient( - 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 =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] - assert args[0] == config.ListPreviewsRequest() - - # 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=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 = 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=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.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=ga_credentials.AnonymousCredentials(), - ) - - # 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, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_previews(request={}) - - assert pager._metadata == metadata - - 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=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__', 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=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__', 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] - assert args[0] == config.DeletePreviewRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_delete_preview_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_preview), - '__call__') as call: - client.delete_preview() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == config.DeletePreviewRequest() - -@pytest.mark.asyncio -async def test_delete_preview_async(transport: str = 'grpc_asyncio', request_type=config.DeletePreviewRequest): - client = ConfigAsyncClient( - 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 = 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] - assert args[0] == config.DeletePreviewRequest() - - # 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=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 = 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=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.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=ga_credentials.AnonymousCredentials(), - ) - - # 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] - assert args[0] == config.ExportPreviewResultRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, config.ExportPreviewResultResponse) - - -def test_export_preview_result_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # 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: - client.export_preview_result() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == config.ExportPreviewResultRequest() - -@pytest.mark.asyncio -async def test_export_preview_result_async(transport: str = 'grpc_asyncio', request_type=config.ExportPreviewResultRequest): - client = ConfigAsyncClient( - 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 =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] - assert args[0] == config.ExportPreviewResultRequest() - - # 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=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 = 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.ListDeploymentsRequest, - dict, -]) -def test_list_deployments_rest(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 = 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 - 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'] - - -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, - including_default_value_fields=False, - 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 - - 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", ))) - - -@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, "pre_list_deployments") as pre: - pre.assert_not_called() - post.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 = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = config.ListDeploymentsResponse.to_json(config.ListDeploymentsResponse()) - - request = config.ListDeploymentsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = config.ListDeploymentsResponse() - - client.list_deployments(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_deployments_rest_bad_request(transport: str = 'rest', request_type=config.ListDeploymentsRequest): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # 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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_deployments(request) - - -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 - - 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 - - -@pytest.mark.parametrize("request_type", [ - config.GetDeploymentRequest, - dict, -]) -def test_get_deployment_rest(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, - ) - - # 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 - 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 - - -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, - including_default_value_fields=False, - 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 - - 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", ))) - - -@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, "pre_get_deployment") as pre: - pre.assert_not_called() - post.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 = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = config.Deployment.to_json(config.Deployment()) - - request = config.GetDeploymentRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = config.Deployment() - - client.get_deployment(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_deployment_rest_bad_request(transport: str = 'rest', request_type=config.GetDeploymentRequest): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # 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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_deployment(request) - - -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 - - 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_get_deployment_rest_error(): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - config.CreateDeploymentRequest, - dict, -]) -def test_create_deployment_rest(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} - # 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 = 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 - response = client.create_deployment(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -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, - including_default_value_fields=False, - 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 - - 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", ))) - - -@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, "pre_create_deployment") as pre: - pre.assert_not_called() - post.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 = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = config.CreateDeploymentRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.create_deployment(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_deployment_rest_bad_request(transport: str = 'rest', request_type=config.CreateDeploymentRequest): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # 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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_deployment(request) - - -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 - - 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_create_deployment_rest_error(): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - config.UpdateDeploymentRequest, - dict, -]) -def test_update_deployment_rest(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} - # 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 = 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 - response = client.update_deployment(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -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, - including_default_value_fields=False, - 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 - - 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", ))) - - -@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, "pre_update_deployment") as pre: - pre.assert_not_called() - post.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 = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = config.UpdateDeploymentRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.update_deployment(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_deployment_rest_bad_request(transport: str = 'rest', request_type=config.UpdateDeploymentRequest): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # 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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_deployment(request) - - -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 - - 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_update_deployment_rest_error(): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - config.DeleteDeploymentRequest, - dict, -]) -def test_delete_deployment_rest(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 = 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 - response = client.delete_deployment(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -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, - including_default_value_fields=False, - 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 - - 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", ))) - - -@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, "pre_delete_deployment") as pre: - pre.assert_not_called() - post.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 = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = config.DeleteDeploymentRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.delete_deployment(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_deployment_rest_bad_request(transport: str = 'rest', request_type=config.DeleteDeploymentRequest): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # 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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_deployment(request) - - -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 - - 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_delete_deployment_rest_error(): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - config.ListRevisionsRequest, - dict, -]) -def test_list_revisions_rest(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 = 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 - 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'] - - -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, - including_default_value_fields=False, - 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 - - 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", ))) - - -@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, "pre_list_revisions") as pre: - pre.assert_not_called() - post.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 = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = config.ListRevisionsResponse.to_json(config.ListRevisionsResponse()) - - request = config.ListRevisionsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = config.ListRevisionsResponse() - - client.list_revisions(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_revisions_rest_bad_request(transport: str = 'rest', request_type=config.ListRevisionsRequest): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # 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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_revisions(request) - - -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 - - 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 - - -@pytest.mark.parametrize("request_type", [ - config.GetRevisionRequest, - dict, -]) -def test_get_revision_rest(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', - ) - - # 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 - 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' - - -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, - including_default_value_fields=False, - 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 - - 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", ))) - - -@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, "pre_get_revision") as pre: - pre.assert_not_called() - post.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 = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = config.Revision.to_json(config.Revision()) - - request = config.GetRevisionRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = config.Revision() - - client.get_revision(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_revision_rest_bad_request(transport: str = 'rest', request_type=config.GetRevisionRequest): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # 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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_revision(request) - - -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 - - 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_revision_rest_error(): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - config.GetResourceRequest, - dict, -]) -def test_get_resource_rest(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 = 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 - 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 - - -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, - including_default_value_fields=False, - 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 - - 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", ))) - - -@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, "pre_get_resource") as pre: - pre.assert_not_called() - post.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 = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = config.Resource.to_json(config.Resource()) - - request = config.GetResourceRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = config.Resource() - - client.get_resource(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_resource_rest_bad_request(transport: str = 'rest', request_type=config.GetResourceRequest): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # 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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_resource(request) - - -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 - - 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_get_resource_rest_error(): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - config.ListResourcesRequest, - dict, -]) -def test_list_resources_rest(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 = 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 - 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'] - - -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, - including_default_value_fields=False, - 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 - - 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", ))) - - -@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, "pre_list_resources") as pre: - pre.assert_not_called() - post.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 = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = config.ListResourcesResponse.to_json(config.ListResourcesResponse()) - - request = config.ListResourcesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = config.ListResourcesResponse() - - client.list_resources(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_resources_rest_bad_request(transport: str = 'rest', request_type=config.ListResourcesRequest): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # 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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_resources(request) - - -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 - - 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 - - -@pytest.mark.parametrize("request_type", [ - config.ExportDeploymentStatefileRequest, - dict, -]) -def test_export_deployment_statefile_rest(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 = 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 - 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' - - -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, - including_default_value_fields=False, - 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 - - 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", ))) - - -@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, "pre_export_deployment_statefile") as pre: - pre.assert_not_called() - post.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 = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = config.Statefile.to_json(config.Statefile()) - - request = config.ExportDeploymentStatefileRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = config.Statefile() - - client.export_deployment_statefile(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_export_deployment_statefile_rest_bad_request(transport: str = 'rest', request_type=config.ExportDeploymentStatefileRequest): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # 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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.export_deployment_statefile(request) - - -def test_export_deployment_statefile_rest_error(): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - config.ExportRevisionStatefileRequest, - dict, -]) -def test_export_revision_statefile_rest(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 = 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 - 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' - - -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, - including_default_value_fields=False, - 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 - - 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", ))) - - -@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, "pre_export_revision_statefile") as pre: - pre.assert_not_called() - post.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 = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = config.Statefile.to_json(config.Statefile()) - - request = config.ExportRevisionStatefileRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = config.Statefile() - - client.export_revision_statefile(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_export_revision_statefile_rest_bad_request(transport: str = 'rest', request_type=config.ExportRevisionStatefileRequest): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # 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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.export_revision_statefile(request) - - -def test_export_revision_statefile_rest_error(): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - config.ImportStatefileRequest, - dict, -]) -def test_import_statefile_rest(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 = 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 - 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' - - -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, - including_default_value_fields=False, - 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 - - 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", ))) - - -@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, "pre_import_statefile") as pre: - pre.assert_not_called() - post.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 = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = config.Statefile.to_json(config.Statefile()) - - request = config.ImportStatefileRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = config.Statefile() - - client.import_statefile(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_import_statefile_rest_bad_request(transport: str = 'rest', request_type=config.ImportStatefileRequest): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # 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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.import_statefile(request) - - -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 - - 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_import_statefile_rest_error(): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - config.DeleteStatefileRequest, - dict, -]) -def test_delete_statefile_rest(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 = Response() - response_value.status_code = 200 - json_return_value = '' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.delete_statefile(request) - - # Establish that the response is the type that we expect. - assert response is None - - -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, - including_default_value_fields=False, - 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 - - 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", ))) - - -@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 = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - - 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_delete_statefile_rest_bad_request(transport: str = 'rest', request_type=config.DeleteStatefileRequest): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # 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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_statefile(request) - - -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 - - 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_delete_statefile_rest_error(): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - config.LockDeploymentRequest, - dict, -]) -def test_lock_deployment_rest(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 = 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 - response = client.lock_deployment(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -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, - including_default_value_fields=False, - 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 - - 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", ))) - - -@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, "pre_lock_deployment") as pre: - pre.assert_not_called() - post.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 = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = config.LockDeploymentRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.lock_deployment(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_lock_deployment_rest_bad_request(transport: str = 'rest', request_type=config.LockDeploymentRequest): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # 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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.lock_deployment(request) - - -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 - - 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_lock_deployment_rest_error(): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - config.UnlockDeploymentRequest, - dict, -]) -def test_unlock_deployment_rest(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 = 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 - response = client.unlock_deployment(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -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, - including_default_value_fields=False, - 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 - - 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", ))) - - -@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, "pre_unlock_deployment") as pre: - pre.assert_not_called() - post.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 = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = config.UnlockDeploymentRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.unlock_deployment(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_unlock_deployment_rest_bad_request(transport: str = 'rest', request_type=config.UnlockDeploymentRequest): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # 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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.unlock_deployment(request) - - -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 - - 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_unlock_deployment_rest_error(): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - config.ExportLockInfoRequest, - dict, -]) -def test_export_lock_info_rest(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 = 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 - 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' - - -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, - including_default_value_fields=False, - 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 - - 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", ))) - - -@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, "pre_export_lock_info") as pre: - pre.assert_not_called() - post.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 = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = config.LockInfo.to_json(config.LockInfo()) - - request = config.ExportLockInfoRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = config.LockInfo() - - client.export_lock_info(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_export_lock_info_rest_bad_request(transport: str = 'rest', request_type=config.ExportLockInfoRequest): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # 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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.export_lock_info(request) - - -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 - - 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_export_lock_info_rest_error(): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - config.CreatePreviewRequest, - dict, -]) -def test_create_preview_rest(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'} - # 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 = 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 - response = client.create_preview(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -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, - including_default_value_fields=False, - 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 - - 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", ))) - - -@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, "pre_create_preview") as pre: - pre.assert_not_called() - post.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 = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = config.CreatePreviewRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.create_preview(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_preview_rest_bad_request(transport: str = 'rest', request_type=config.CreatePreviewRequest): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # 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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_preview(request) - - -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 - - 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_create_preview_rest_error(): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - config.GetPreviewRequest, - dict, -]) -def test_get_preview_rest(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', - ) - - # 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 - 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' - - -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, - including_default_value_fields=False, - 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 - - 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", ))) - - -@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, "pre_get_preview") as pre: - pre.assert_not_called() - post.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 = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = config.Preview.to_json(config.Preview()) - - request = config.GetPreviewRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = config.Preview() - - client.get_preview(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_preview_rest_bad_request(transport: str = 'rest', request_type=config.GetPreviewRequest): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # 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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_preview(request) - - -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 - - 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_get_preview_rest_error(): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - config.ListPreviewsRequest, - dict, -]) -def test_list_previews_rest(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 = 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 - 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'] - - -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, - including_default_value_fields=False, - 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 - - 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", ))) - - -@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, "pre_list_previews") as pre: - pre.assert_not_called() - post.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 = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = config.ListPreviewsResponse.to_json(config.ListPreviewsResponse()) - - request = config.ListPreviewsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = config.ListPreviewsResponse() - - client.list_previews(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_previews_rest_bad_request(transport: str = 'rest', request_type=config.ListPreviewsRequest): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # 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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_previews(request) - - -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 - - 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 - - -@pytest.mark.parametrize("request_type", [ - config.DeletePreviewRequest, - dict, -]) -def test_delete_preview_rest(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 = 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 - response = client.delete_preview(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -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, - including_default_value_fields=False, - 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 - - 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", ))) - - -@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, "pre_delete_preview") as pre: - pre.assert_not_called() - post.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 = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = config.DeletePreviewRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.delete_preview(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_preview_rest_bad_request(transport: str = 'rest', request_type=config.DeletePreviewRequest): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # 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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_preview(request) - - -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 - - 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_delete_preview_rest_error(): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - config.ExportPreviewResultRequest, - dict, -]) -def test_export_preview_result_rest(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 = 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 - response = client.export_preview_result(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, config.ExportPreviewResultResponse) - - -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, - including_default_value_fields=False, - 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 - - 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", ))) - - -@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, "pre_export_preview_result") as pre: - pre.assert_not_called() - post.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 = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = config.ExportPreviewResultResponse.to_json(config.ExportPreviewResultResponse()) - - request = config.ExportPreviewResultRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = config.ExportPreviewResultResponse() - - client.export_preview_result(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_export_preview_result_rest_bad_request(transport: str = 'rest', request_type=config.ExportPreviewResultRequest): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # 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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.export_preview_result(request) - - -def test_export_preview_result_rest_error(): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -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 = mock.Mock() - 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() - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "rest", -]) -def test_transport_kind(transport_name): - transport = ConfigClient.get_transport_class(transport_name)( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert transport.kind == transport_name - -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', - '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) - - -def test_config_rest_lro_client(): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - transport = client.transport - - # Ensure that we have a 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 - - -@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 -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_revision_path(): - project = "scallop" - location = "abalone" - deployment = "squid" - revision = "clam" - 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": "whelk", - "location": "octopus", - "deployment": "oyster", - "revision": "nudibranch", - } - 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 = "cuttlefish" - service_account = "mussel" - 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": "winkle", - "service_account": "nautilus", - } - 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_worker_pool_path(): - project = "scallop" - location = "abalone" - worker_pool = "squid" - 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": "clam", - "location": "whelk", - "worker_pool": "octopus", - } - 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 = "oyster" - 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": "nudibranch", - } - 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 = "cuttlefish" - expected = "folders/{folder}".format(folder=folder, ) - actual = ConfigClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "mussel", - } - 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 = "winkle" - expected = "organizations/{organization}".format(organization=organization, ) - actual = ConfigClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nautilus", - } - 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 = "scallop" - expected = "projects/{project}".format(project=project, ) - actual = ConfigClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "abalone", - } - 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 = "squid" - location = "clam" - 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": "whelk", - "location": "octopus", - } - 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) - -@pytest.mark.asyncio -async def test_transport_close_async(): - client = ConfigAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - 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_get_location_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.GetLocationRequest): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - 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(type(client.transport._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 = 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 - - 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(transport: str = 'rest', request_type=locations_pb2.ListLocationsRequest): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - 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(type(client.transport._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 = 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 - - 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(transport: str = 'rest', request_type=iam_policy_pb2.GetIamPolicyRequest): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - 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(type(client.transport._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 = 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 - - 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(transport: str = 'rest', request_type=iam_policy_pb2.SetIamPolicyRequest): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - 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(type(client.transport._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 = 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 - - 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(transport: str = 'rest', request_type=iam_policy_pb2.TestIamPermissionsRequest): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - 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(type(client.transport._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 = 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 - - 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(transport: str = 'rest', request_type=operations_pb2.CancelOperationRequest): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - 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(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 = Response() - response_value.status_code = 200 - json_return_value = '{}' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - 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(transport: str = 'rest', request_type=operations_pb2.DeleteOperationRequest): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - 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(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 = Response() - response_value.status_code = 200 - json_return_value = '{}' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - 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(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - 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(type(client.transport._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 = 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 - - 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(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - 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() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - 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(type(client.transport._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 = 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 - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - -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=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 = 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=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 = 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=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 = 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=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 = 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=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 = 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=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 = 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=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 = 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=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 = 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=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 = 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=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 = 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=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 = 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=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 = 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=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 = 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=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 = 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=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 = 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=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 = 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=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 = 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=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 = 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=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. - # 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=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 = 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=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 = 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=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 = 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=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 = 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=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 = 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=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 = 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=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 = 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=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 = 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(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "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, - 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 b86f5ddc9ec0..ebea67cebc62 100644 --- a/packages/google-cloud-config/google/cloud/config/__init__.py +++ b/packages/google-cloud-config/google/cloud/config/__init__.py @@ -23,20 +23,27 @@ from google.cloud.config_v1.types.config import ( ApplyResults, CreateDeploymentRequest, + CreatePreviewRequest, DeleteDeploymentRequest, + DeletePreviewRequest, DeleteStatefileRequest, Deployment, DeploymentOperationMetadata, ExportDeploymentStatefileRequest, ExportLockInfoRequest, + ExportPreviewResultRequest, + ExportPreviewResultResponse, ExportRevisionStatefileRequest, GetDeploymentRequest, + GetPreviewRequest, GetResourceRequest, GetRevisionRequest, GitSource, ImportStatefileRequest, ListDeploymentsRequest, ListDeploymentsResponse, + ListPreviewsRequest, + ListPreviewsResponse, ListResourcesRequest, ListResourcesResponse, ListRevisionsRequest, @@ -44,6 +51,10 @@ LockDeploymentRequest, LockInfo, OperationMetadata, + Preview, + PreviewArtifacts, + PreviewOperationMetadata, + PreviewResult, Resource, ResourceCAIInfo, ResourceTerraformInfo, @@ -62,20 +73,27 @@ "ConfigAsyncClient", "ApplyResults", "CreateDeploymentRequest", + "CreatePreviewRequest", "DeleteDeploymentRequest", + "DeletePreviewRequest", "DeleteStatefileRequest", "Deployment", "DeploymentOperationMetadata", "ExportDeploymentStatefileRequest", "ExportLockInfoRequest", + "ExportPreviewResultRequest", + "ExportPreviewResultResponse", "ExportRevisionStatefileRequest", "GetDeploymentRequest", + "GetPreviewRequest", "GetResourceRequest", "GetRevisionRequest", "GitSource", "ImportStatefileRequest", "ListDeploymentsRequest", "ListDeploymentsResponse", + "ListPreviewsRequest", + "ListPreviewsResponse", "ListResourcesRequest", "ListResourcesResponse", "ListRevisionsRequest", @@ -83,6 +101,10 @@ "LockDeploymentRequest", "LockInfo", "OperationMetadata", + "Preview", + "PreviewArtifacts", + "PreviewOperationMetadata", + "PreviewResult", "Resource", "ResourceCAIInfo", "ResourceTerraformInfo", diff --git a/packages/google-cloud-config/google/cloud/config/gapic_version.py b/packages/google-cloud-config/google/cloud/config/gapic_version.py index cf99f3acb1ee..360a0d13ebdd 100644 --- a/packages/google-cloud-config/google/cloud/config/gapic_version.py +++ b/packages/google-cloud-config/google/cloud/config/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.1.2" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} 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 a407a3aa0ff8..0dd38e23e39f 100644 --- a/packages/google-cloud-config/google/cloud/config_v1/__init__.py +++ b/packages/google-cloud-config/google/cloud/config_v1/__init__.py @@ -22,20 +22,27 @@ from .types.config import ( ApplyResults, CreateDeploymentRequest, + CreatePreviewRequest, DeleteDeploymentRequest, + DeletePreviewRequest, DeleteStatefileRequest, Deployment, DeploymentOperationMetadata, ExportDeploymentStatefileRequest, ExportLockInfoRequest, + ExportPreviewResultRequest, + ExportPreviewResultResponse, ExportRevisionStatefileRequest, GetDeploymentRequest, + GetPreviewRequest, GetResourceRequest, GetRevisionRequest, GitSource, ImportStatefileRequest, ListDeploymentsRequest, ListDeploymentsResponse, + ListPreviewsRequest, + ListPreviewsResponse, ListResourcesRequest, ListResourcesResponse, ListRevisionsRequest, @@ -43,6 +50,10 @@ LockDeploymentRequest, LockInfo, OperationMetadata, + Preview, + PreviewArtifacts, + PreviewOperationMetadata, + PreviewResult, Resource, ResourceCAIInfo, ResourceTerraformInfo, @@ -61,20 +72,27 @@ "ApplyResults", "ConfigClient", "CreateDeploymentRequest", + "CreatePreviewRequest", "DeleteDeploymentRequest", + "DeletePreviewRequest", "DeleteStatefileRequest", "Deployment", "DeploymentOperationMetadata", "ExportDeploymentStatefileRequest", "ExportLockInfoRequest", + "ExportPreviewResultRequest", + "ExportPreviewResultResponse", "ExportRevisionStatefileRequest", "GetDeploymentRequest", + "GetPreviewRequest", "GetResourceRequest", "GetRevisionRequest", "GitSource", "ImportStatefileRequest", "ListDeploymentsRequest", "ListDeploymentsResponse", + "ListPreviewsRequest", + "ListPreviewsResponse", "ListResourcesRequest", "ListResourcesResponse", "ListRevisionsRequest", @@ -82,6 +100,10 @@ "LockDeploymentRequest", "LockInfo", "OperationMetadata", + "Preview", + "PreviewArtifacts", + "PreviewOperationMetadata", + "PreviewResult", "Resource", "ResourceCAIInfo", "ResourceTerraformInfo", diff --git a/packages/google-cloud-config/google/cloud/config_v1/gapic_metadata.json b/packages/google-cloud-config/google/cloud/config_v1/gapic_metadata.json index 65de7b78a0aa..190bb0825b1c 100644 --- a/packages/google-cloud-config/google/cloud/config_v1/gapic_metadata.json +++ b/packages/google-cloud-config/google/cloud/config_v1/gapic_metadata.json @@ -15,11 +15,21 @@ "create_deployment" ] }, + "CreatePreview": { + "methods": [ + "create_preview" + ] + }, "DeleteDeployment": { "methods": [ "delete_deployment" ] }, + "DeletePreview": { + "methods": [ + "delete_preview" + ] + }, "DeleteStatefile": { "methods": [ "delete_statefile" @@ -35,6 +45,11 @@ "export_lock_info" ] }, + "ExportPreviewResult": { + "methods": [ + "export_preview_result" + ] + }, "ExportRevisionStatefile": { "methods": [ "export_revision_statefile" @@ -45,6 +60,11 @@ "get_deployment" ] }, + "GetPreview": { + "methods": [ + "get_preview" + ] + }, "GetResource": { "methods": [ "get_resource" @@ -65,6 +85,11 @@ "list_deployments" ] }, + "ListPreviews": { + "methods": [ + "list_previews" + ] + }, "ListResources": { "methods": [ "list_resources" @@ -100,11 +125,21 @@ "create_deployment" ] }, + "CreatePreview": { + "methods": [ + "create_preview" + ] + }, "DeleteDeployment": { "methods": [ "delete_deployment" ] }, + "DeletePreview": { + "methods": [ + "delete_preview" + ] + }, "DeleteStatefile": { "methods": [ "delete_statefile" @@ -120,6 +155,11 @@ "export_lock_info" ] }, + "ExportPreviewResult": { + "methods": [ + "export_preview_result" + ] + }, "ExportRevisionStatefile": { "methods": [ "export_revision_statefile" @@ -130,6 +170,11 @@ "get_deployment" ] }, + "GetPreview": { + "methods": [ + "get_preview" + ] + }, "GetResource": { "methods": [ "get_resource" @@ -150,6 +195,11 @@ "list_deployments" ] }, + "ListPreviews": { + "methods": [ + "list_previews" + ] + }, "ListResources": { "methods": [ "list_resources" @@ -185,11 +235,21 @@ "create_deployment" ] }, + "CreatePreview": { + "methods": [ + "create_preview" + ] + }, "DeleteDeployment": { "methods": [ "delete_deployment" ] }, + "DeletePreview": { + "methods": [ + "delete_preview" + ] + }, "DeleteStatefile": { "methods": [ "delete_statefile" @@ -205,6 +265,11 @@ "export_lock_info" ] }, + "ExportPreviewResult": { + "methods": [ + "export_preview_result" + ] + }, "ExportRevisionStatefile": { "methods": [ "export_revision_statefile" @@ -215,6 +280,11 @@ "get_deployment" ] }, + "GetPreview": { + "methods": [ + "get_preview" + ] + }, "GetResource": { "methods": [ "get_resource" @@ -235,6 +305,11 @@ "list_deployments" ] }, + "ListPreviews": { + "methods": [ + "list_previews" + ] + }, "ListResources": { "methods": [ "list_resources" diff --git a/packages/google-cloud-config/google/cloud/config_v1/gapic_version.py b/packages/google-cloud-config/google/cloud/config_v1/gapic_version.py index cf99f3acb1ee..360a0d13ebdd 100644 --- a/packages/google-cloud-config/google/cloud/config_v1/gapic_version.py +++ b/packages/google-cloud-config/google/cloud/config_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.1.2" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} 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 8f6ab9857596..e6752efa8a85 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 @@ -50,6 +50,7 @@ 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 google.cloud.config_v1.services.config import pagers from google.cloud.config_v1.types import config @@ -72,6 +73,8 @@ class ConfigAsyncClient: 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) revision_path = staticmethod(ConfigClient.revision_path) @@ -1997,6 +2000,553 @@ async def sample_export_lock_info(): # 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, str]] = (), + ) -> 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" + + 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, str]]): Strings which should be + sent along with the request as metadata. + + 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. + has_flattened_params = any([parent, preview]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + 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 = gapic_v1.method_async.wrap_method( + self._client._transport.create_preview, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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),)), + ) + + # 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + 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 = gapic_v1.method_async.wrap_method( + self._client._transport.get_preview, + default_timeout=None, + client_info=DEFAULT_CLIENT_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),)), + ) + + # 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + 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 = gapic_v1.method_async.wrap_method( + self._client._transport.list_previews, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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),)), + ) + + # 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, + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + 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 = gapic_v1.method_async.wrap_method( + self._client._transport.delete_preview, + default_timeout=None, + client_info=DEFAULT_CLIENT_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),)), + ) + + # 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.config_v1.types.ExportPreviewResultResponse: + A response to ExportPreviewResult call. Contains preview + results. + + """ + # Create or coerce a protobuf request object. + request = config.ExportPreviewResultRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.export_preview_result, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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),)), + ) + + # 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, 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 d3ff68354028..354b94abeb93 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 @@ -54,6 +54,7 @@ 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 google.cloud.config_v1.services.config import pagers from google.cloud.config_v1.types import config @@ -211,6 +212,28 @@ def parse_deployment_path(path: str) -> Dict[str, str]: ) 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, @@ -2328,6 +2351,554 @@ def sample_export_lock_info(): # 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, str]] = (), + ) -> 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" + + 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, str]]): Strings which should be + sent along with the request as metadata. + + 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. + has_flattened_params = any([parent, preview]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a config.CreatePreviewRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + 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),)), + ) + + # 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a config.GetPreviewRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + 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),)), + ) + + # 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a config.ListPreviewsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + 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),)), + ) + + # 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, + 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a config.DeletePreviewRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + 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),)), + ) + + # 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, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.config_v1.types.ExportPreviewResultResponse: + A response to ExportPreviewResult call. Contains preview + results. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a config.ExportPreviewResultRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + 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),)), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + def __enter__(self) -> "ConfigClient": return self diff --git a/packages/google-cloud-config/google/cloud/config_v1/services/config/pagers.py b/packages/google-cloud-config/google/cloud/config_v1/services/config/pagers.py index d0ccc958ea38..8f74585f587d 100644 --- a/packages/google-cloud-config/google/cloud/config_v1/services/config/pagers.py +++ b/packages/google-cloud-config/google/cloud/config_v1/services/config/pagers.py @@ -409,3 +409,131 @@ async def 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, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """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. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = config.ListPreviewsRequest(request) + self._response = response + 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, 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, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """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. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = config.ListPreviewsRequest(request) + self._response = response + 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, 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) diff --git a/packages/google-cloud-config/google/cloud/config_v1/services/config/transports/base.py b/packages/google-cloud-config/google/cloud/config_v1/services/config/transports/base.py index a5139f21b4ce..5ca64f211d1a 100644 --- a/packages/google-cloud-config/google/cloud/config_v1/services/config/transports/base.py +++ b/packages/google-cloud-config/google/cloud/config_v1/services/config/transports/base.py @@ -207,6 +207,31 @@ def _prep_wrapped_messages(self, client_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, + ), } def close(self): @@ -367,6 +392,53 @@ def export_lock_info( ]: 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_operations( self, diff --git a/packages/google-cloud-config/google/cloud/config_v1/services/config/transports/grpc.py b/packages/google-cloud-config/google/cloud/config_v1/services/config/transports/grpc.py index 16b83b8ff3fa..da503d656520 100644 --- a/packages/google-cloud-config/google/cloud/config_v1/services/config/transports/grpc.py +++ b/packages/google-cloud-config/google/cloud/config_v1/services/config/transports/grpc.py @@ -670,6 +670,137 @@ def export_lock_info( ) 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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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"] + def close(self): self.grpc_channel.close() diff --git a/packages/google-cloud-config/google/cloud/config_v1/services/config/transports/grpc_asyncio.py b/packages/google-cloud-config/google/cloud/config_v1/services/config/transports/grpc_asyncio.py index 84eaa9ba992c..c02df0a05a20 100644 --- a/packages/google-cloud-config/google/cloud/config_v1/services/config/transports/grpc_asyncio.py +++ b/packages/google-cloud-config/google/cloud/config_v1/services/config/transports/grpc_asyncio.py @@ -695,6 +695,140 @@ def export_lock_info( ) 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.grpc_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.grpc_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.grpc_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.grpc_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.grpc_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"] + def close(self): return self.grpc_channel.close() diff --git a/packages/google-cloud-config/google/cloud/config_v1/services/config/transports/rest.py b/packages/google-cloud-config/google/cloud/config_v1/services/config/transports/rest.py index 830a3d73360d..321e415304ea 100644 --- a/packages/google-cloud-config/google/cloud/config_v1/services/config/transports/rest.py +++ b/packages/google-cloud-config/google/cloud/config_v1/services/config/transports/rest.py @@ -83,6 +83,14 @@ 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 @@ -91,6 +99,14 @@ 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 @@ -111,6 +127,14 @@ 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 @@ -127,6 +151,14 @@ 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 @@ -159,6 +191,14 @@ 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_resources(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -228,6 +268,27 @@ def post_create_deployment( """ return response + def pre_create_preview( + self, request: config.CreatePreviewRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[config.CreatePreviewRequest, Sequence[Tuple[str, str]]]: + """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 + + 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_deployment( self, request: config.DeleteDeploymentRequest, @@ -251,6 +312,27 @@ def post_delete_deployment( """ return response + def pre_delete_preview( + self, request: config.DeletePreviewRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[config.DeletePreviewRequest, Sequence[Tuple[str, str]]]: + """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 + + 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_statefile( self, request: config.DeleteStatefileRequest, @@ -305,6 +387,29 @@ def post_export_lock_info(self, response: config.LockInfo) -> config.LockInfo: """ return response + def pre_export_preview_result( + self, + request: config.ExportPreviewResultRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[config.ExportPreviewResultRequest, Sequence[Tuple[str, str]]]: + """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 + + 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_export_revision_statefile( self, request: config.ExportRevisionStatefileRequest, @@ -347,6 +452,25 @@ def post_get_deployment(self, response: config.Deployment) -> config.Deployment: """ return response + def pre_get_preview( + self, request: config.GetPreviewRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[config.GetPreviewRequest, Sequence[Tuple[str, str]]]: + """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 + + 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_resource( self, request: config.GetResourceRequest, metadata: Sequence[Tuple[str, str]] ) -> Tuple[config.GetResourceRequest, Sequence[Tuple[str, str]]]: @@ -429,6 +553,27 @@ def post_list_deployments( """ return response + def pre_list_previews( + self, request: config.ListPreviewsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[config.ListPreviewsRequest, Sequence[Tuple[str, str]]]: + """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 + + 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_resources( self, request: config.ListResourcesRequest, metadata: Sequence[Tuple[str, str]] ) -> Tuple[config.ListResourcesRequest, Sequence[Tuple[str, str]]]: @@ -990,6 +1135,102 @@ def __call__( resp = self._interceptor.post_create_deployment(resp) return resp + class _CreatePreview(ConfigRestStub): + def __hash__(self): + return hash("CreatePreview") + + __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 + } + + def __call__( + self, + request: config.CreatePreviewRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=projects/*/locations/*}/previews", + "body": "preview", + }, + ] + request, metadata = self._interceptor.pre_create_preview(request, metadata) + pb_request = config.CreatePreviewRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=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) + return resp + class _DeleteDeployment(ConfigRestStub): def __hash__(self): return hash("DeleteDeployment") @@ -1037,10 +1278,97 @@ def __call__( "uri": "/v1/{name=projects/*/locations/*/deployments/*}", }, ] - request, metadata = self._interceptor.pre_delete_deployment( - request, metadata - ) - pb_request = config.DeleteDeploymentRequest.pb(request) + request, metadata = self._interceptor.pre_delete_deployment( + request, metadata + ) + pb_request = config.DeleteDeploymentRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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) + return resp + + class _DeletePreview(ConfigRestStub): + def __hash__(self): + return hash("DeletePreview") + + __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 + } + + def __call__( + self, + request: config.DeletePreviewRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1/{name=projects/*/locations/*/previews/*}", + }, + ] + request, metadata = self._interceptor.pre_delete_preview(request, metadata) + pb_request = config.DeletePreviewRequest.pb(request) transcoded_request = path_template.transcode(http_options, pb_request) uri = transcoded_request["uri"] @@ -1076,7 +1404,7 @@ def __call__( # Return the response resp = operations_pb2.Operation() json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_delete_deployment(resp) + resp = self._interceptor.post_delete_preview(resp) return resp class _DeleteStatefile(ConfigRestStub): @@ -1358,6 +1686,105 @@ def __call__( resp = self._interceptor.post_export_lock_info(resp) return resp + class _ExportPreviewResult(ConfigRestStub): + def __hash__(self): + return hash("ExportPreviewResult") + + __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 + } + + def __call__( + self, + request: config.ExportPreviewResultRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.config.ExportPreviewResultResponse: + A response to ``ExportPreviewResult`` call. Contains + preview results. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=projects/*/locations/*/previews/*}:export", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_export_preview_result( + request, metadata + ) + pb_request = config.ExportPreviewResultRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=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) + return resp + class _ExportRevisionStatefile(ConfigRestStub): def __hash__(self): return hash("ExportRevisionStatefile") @@ -1548,6 +1975,97 @@ def __call__( resp = self._interceptor.post_get_deployment(resp) return resp + class _GetPreview(ConfigRestStub): + def __hash__(self): + return hash("GetPreview") + + __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 + } + + def __call__( + self, + request: config.GetPreviewRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + 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: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/previews/*}", + }, + ] + request, metadata = self._interceptor.pre_get_preview(request, metadata) + pb_request = config.GetPreviewRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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) + return resp + class _GetResource(ConfigRestStub): def __hash__(self): return hash("GetResource") @@ -1919,6 +2437,95 @@ def __call__( resp = self._interceptor.post_list_deployments(resp) return resp + class _ListPreviews(ConfigRestStub): + def __hash__(self): + return hash("ListPreviews") + + __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 + } + + def __call__( + self, + request: config.ListPreviewsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.config.ListPreviewsResponse: + A response to a ``ListPreviews`` call. Contains a list + of Previews. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=projects/*/locations/*}/previews", + }, + ] + request, metadata = self._interceptor.pre_list_previews(request, metadata) + pb_request = config.ListPreviewsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # 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) + return resp + class _ListResources(ConfigRestStub): def __hash__(self): return hash("ListResources") @@ -2399,6 +3006,14 @@ def create_deployment( # 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, @@ -2407,6 +3022,14 @@ def delete_deployment( # 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, @@ -2431,6 +3054,16 @@ def export_lock_info( # 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, @@ -2447,6 +3080,12 @@ def get_deployment( # 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. @@ -2475,6 +3114,14 @@ def list_deployments( # 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_resources( self, 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 5ce94d9c52f7..6c87a43cf63b 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 @@ -16,20 +16,27 @@ from .config import ( ApplyResults, CreateDeploymentRequest, + CreatePreviewRequest, DeleteDeploymentRequest, + DeletePreviewRequest, DeleteStatefileRequest, Deployment, DeploymentOperationMetadata, ExportDeploymentStatefileRequest, ExportLockInfoRequest, + ExportPreviewResultRequest, + ExportPreviewResultResponse, ExportRevisionStatefileRequest, GetDeploymentRequest, + GetPreviewRequest, GetResourceRequest, GetRevisionRequest, GitSource, ImportStatefileRequest, ListDeploymentsRequest, ListDeploymentsResponse, + ListPreviewsRequest, + ListPreviewsResponse, ListResourcesRequest, ListResourcesResponse, ListRevisionsRequest, @@ -37,6 +44,10 @@ LockDeploymentRequest, LockInfo, OperationMetadata, + Preview, + PreviewArtifacts, + PreviewOperationMetadata, + PreviewResult, Resource, ResourceCAIInfo, ResourceTerraformInfo, @@ -53,20 +64,27 @@ __all__ = ( "ApplyResults", "CreateDeploymentRequest", + "CreatePreviewRequest", "DeleteDeploymentRequest", + "DeletePreviewRequest", "DeleteStatefileRequest", "Deployment", "DeploymentOperationMetadata", "ExportDeploymentStatefileRequest", "ExportLockInfoRequest", + "ExportPreviewResultRequest", + "ExportPreviewResultResponse", "ExportRevisionStatefileRequest", "GetDeploymentRequest", + "GetPreviewRequest", "GetResourceRequest", "GetRevisionRequest", "GitSource", "ImportStatefileRequest", "ListDeploymentsRequest", "ListDeploymentsResponse", + "ListPreviewsRequest", + "ListPreviewsResponse", "ListResourcesRequest", "ListResourcesResponse", "ListRevisionsRequest", @@ -74,6 +92,10 @@ "LockDeploymentRequest", "LockInfo", "OperationMetadata", + "Preview", + "PreviewArtifacts", + "PreviewOperationMetadata", + "PreviewResult", "Resource", "ResourceCAIInfo", "ResourceTerraformInfo", 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 91145d025753..589c58143948 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 @@ -60,6 +60,17 @@ "UnlockDeploymentRequest", "ExportLockInfoRequest", "LockInfo", + "Preview", + "PreviewOperationMetadata", + "PreviewArtifacts", + "CreatePreviewRequest", + "GetPreviewRequest", + "ListPreviewsRequest", + "ListPreviewsResponse", + "DeletePreviewRequest", + "ExportPreviewResultRequest", + "ExportPreviewResultResponse", + "PreviewResult", }, ) @@ -889,6 +900,11 @@ class DeletePolicy(proto.Enum): 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: @@ -896,6 +912,11 @@ class OperationMetadata(proto.Message): 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 @@ -929,6 +950,12 @@ class OperationMetadata(proto.Message): 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, @@ -1799,4 +1826,622 @@ class LockInfo(proto.Message): ) +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): + Optional. Optional service account. If + omitted, the deployment resource reference must + be provided, and the service account attached to + the deployment will be used. + 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. + """ + + 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, + ) + + +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. + """ + 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 + + 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 or + set to 0, all resources will be returned. + 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][]s. + 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, + ) + + __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_create_preview_async.py b/packages/google-cloud-config/samples/generated_samples/config_v1_generated_config_create_preview_async.py similarity index 100% rename from owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_create_preview_async.py rename to packages/google-cloud-config/samples/generated_samples/config_v1_generated_config_create_preview_async.py diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_create_preview_sync.py b/packages/google-cloud-config/samples/generated_samples/config_v1_generated_config_create_preview_sync.py similarity index 100% rename from owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_create_preview_sync.py rename to packages/google-cloud-config/samples/generated_samples/config_v1_generated_config_create_preview_sync.py diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_delete_preview_async.py b/packages/google-cloud-config/samples/generated_samples/config_v1_generated_config_delete_preview_async.py similarity index 100% rename from owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_delete_preview_async.py rename to packages/google-cloud-config/samples/generated_samples/config_v1_generated_config_delete_preview_async.py diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_delete_preview_sync.py b/packages/google-cloud-config/samples/generated_samples/config_v1_generated_config_delete_preview_sync.py similarity index 100% rename from owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_delete_preview_sync.py rename to packages/google-cloud-config/samples/generated_samples/config_v1_generated_config_delete_preview_sync.py diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_export_preview_result_async.py b/packages/google-cloud-config/samples/generated_samples/config_v1_generated_config_export_preview_result_async.py similarity index 100% rename from owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_export_preview_result_async.py rename to packages/google-cloud-config/samples/generated_samples/config_v1_generated_config_export_preview_result_async.py diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_export_preview_result_sync.py b/packages/google-cloud-config/samples/generated_samples/config_v1_generated_config_export_preview_result_sync.py similarity index 100% rename from owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_export_preview_result_sync.py rename to packages/google-cloud-config/samples/generated_samples/config_v1_generated_config_export_preview_result_sync.py diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_preview_async.py b/packages/google-cloud-config/samples/generated_samples/config_v1_generated_config_get_preview_async.py similarity index 100% rename from owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_preview_async.py rename to packages/google-cloud-config/samples/generated_samples/config_v1_generated_config_get_preview_async.py diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_preview_sync.py b/packages/google-cloud-config/samples/generated_samples/config_v1_generated_config_get_preview_sync.py similarity index 100% rename from owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_get_preview_sync.py rename to packages/google-cloud-config/samples/generated_samples/config_v1_generated_config_get_preview_sync.py diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_previews_async.py b/packages/google-cloud-config/samples/generated_samples/config_v1_generated_config_list_previews_async.py similarity index 100% rename from owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_previews_async.py rename to packages/google-cloud-config/samples/generated_samples/config_v1_generated_config_list_previews_async.py diff --git a/owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_previews_sync.py b/packages/google-cloud-config/samples/generated_samples/config_v1_generated_config_list_previews_sync.py similarity index 100% rename from owl-bot-staging/google-cloud-config/v1/samples/generated_samples/config_v1_generated_config_list_previews_sync.py rename to packages/google-cloud-config/samples/generated_samples/config_v1_generated_config_list_previews_sync.py diff --git a/packages/google-cloud-config/samples/generated_samples/snippet_metadata_google.cloud.config.v1.json b/packages/google-cloud-config/samples/generated_samples/snippet_metadata_google.cloud.config.v1.json index 1dc05379a40f..9f9d26c92521 100644 --- a/packages/google-cloud-config/samples/generated_samples/snippet_metadata_google.cloud.config.v1.json +++ b/packages/google-cloud-config/samples/generated_samples/snippet_metadata_google.cloud.config.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-config", - "version": "0.1.2" + "version": "0.1.0" }, "snippets": [ { @@ -188,6 +188,175 @@ ], "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, str]" + } + ], + "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": 59, + "start": 27, + "type": "FULL" + }, + { + "end": 59, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 56, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 60, + "start": 57, + "type": "RESPONSE_HANDLING" + } + ], + "title": "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, str]" + } + ], + "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": 59, + "start": 27, + "type": "FULL" + }, + { + "end": 59, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 56, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 60, + "start": 57, + "type": "RESPONSE_HANDLING" + } + ], + "title": "config_v1_generated_config_create_preview_sync.py" + }, { "canonical": true, "clientMethod": { @@ -357,19 +526,19 @@ "fullName": "google.cloud.config_v1.ConfigAsyncClient", "shortName": "ConfigAsyncClient" }, - "fullName": "google.cloud.config_v1.ConfigAsyncClient.delete_statefile", + "fullName": "google.cloud.config_v1.ConfigAsyncClient.delete_preview", "method": { - "fullName": "google.cloud.config.v1.Config.DeleteStatefile", + "fullName": "google.cloud.config.v1.Config.DeletePreview", "service": { "fullName": "google.cloud.config.v1.Config", "shortName": "Config" }, - "shortName": "DeleteStatefile" + "shortName": "DeletePreview" }, "parameters": [ { "name": "request", - "type": "google.cloud.config_v1.types.DeleteStatefileRequest" + "type": "google.cloud.config_v1.types.DeletePreviewRequest" }, { "name": "name", @@ -388,21 +557,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "shortName": "delete_statefile" + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_preview" }, - "description": "Sample for DeleteStatefile", - "file": "config_v1_generated_config_delete_statefile_async.py", + "description": "Sample for DeletePreview", + "file": "config_v1_generated_config_delete_preview_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "config_v1_generated_Config_DeleteStatefile_async", + "regionTag": "config_v1_generated_Config_DeletePreview_async", "segments": [ { - "end": 50, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 50, + "end": 55, "start": 27, "type": "SHORT" }, @@ -412,20 +582,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "start": 47, + "end": 52, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 51, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "config_v1_generated_config_delete_statefile_async.py" + "title": "config_v1_generated_config_delete_preview_async.py" }, { "canonical": true, @@ -434,19 +606,19 @@ "fullName": "google.cloud.config_v1.ConfigClient", "shortName": "ConfigClient" }, - "fullName": "google.cloud.config_v1.ConfigClient.delete_statefile", + "fullName": "google.cloud.config_v1.ConfigClient.delete_preview", "method": { - "fullName": "google.cloud.config.v1.Config.DeleteStatefile", + "fullName": "google.cloud.config.v1.Config.DeletePreview", "service": { "fullName": "google.cloud.config.v1.Config", "shortName": "Config" }, - "shortName": "DeleteStatefile" + "shortName": "DeletePreview" }, "parameters": [ { "name": "request", - "type": "google.cloud.config_v1.types.DeleteStatefileRequest" + "type": "google.cloud.config_v1.types.DeletePreviewRequest" }, { "name": "name", @@ -465,21 +637,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "shortName": "delete_statefile" + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_preview" }, - "description": "Sample for DeleteStatefile", - "file": "config_v1_generated_config_delete_statefile_sync.py", + "description": "Sample for DeletePreview", + "file": "config_v1_generated_config_delete_preview_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "config_v1_generated_Config_DeleteStatefile_sync", + "regionTag": "config_v1_generated_Config_DeletePreview_sync", "segments": [ { - "end": 50, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 50, + "end": 55, "start": 27, "type": "SHORT" }, @@ -489,20 +662,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "start": 47, + "end": 52, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 51, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "config_v1_generated_config_delete_statefile_sync.py" + "title": "config_v1_generated_config_delete_preview_sync.py" }, { "canonical": true, @@ -512,19 +687,23 @@ "fullName": "google.cloud.config_v1.ConfigAsyncClient", "shortName": "ConfigAsyncClient" }, - "fullName": "google.cloud.config_v1.ConfigAsyncClient.export_deployment_statefile", + "fullName": "google.cloud.config_v1.ConfigAsyncClient.delete_statefile", "method": { - "fullName": "google.cloud.config.v1.Config.ExportDeploymentStatefile", + "fullName": "google.cloud.config.v1.Config.DeleteStatefile", "service": { "fullName": "google.cloud.config.v1.Config", "shortName": "Config" }, - "shortName": "ExportDeploymentStatefile" + "shortName": "DeleteStatefile" }, "parameters": [ { "name": "request", - "type": "google.cloud.config_v1.types.ExportDeploymentStatefileRequest" + "type": "google.cloud.config_v1.types.DeleteStatefileRequest" + }, + { + "name": "name", + "type": "str" }, { "name": "retry", @@ -539,22 +718,21 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.config_v1.types.Statefile", - "shortName": "export_deployment_statefile" + "shortName": "delete_statefile" }, - "description": "Sample for ExportDeploymentStatefile", - "file": "config_v1_generated_config_export_deployment_statefile_async.py", + "description": "Sample for DeleteStatefile", + "file": "config_v1_generated_config_delete_statefile_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "config_v1_generated_Config_ExportDeploymentStatefile_async", + "regionTag": "config_v1_generated_Config_DeleteStatefile_async", "segments": [ { - "end": 51, + "end": 50, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 50, "start": 27, "type": "SHORT" }, @@ -564,22 +742,20 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 51, "type": "RESPONSE_HANDLING" } ], - "title": "config_v1_generated_config_export_deployment_statefile_async.py" + "title": "config_v1_generated_config_delete_statefile_async.py" }, { "canonical": true, @@ -588,19 +764,23 @@ "fullName": "google.cloud.config_v1.ConfigClient", "shortName": "ConfigClient" }, - "fullName": "google.cloud.config_v1.ConfigClient.export_deployment_statefile", + "fullName": "google.cloud.config_v1.ConfigClient.delete_statefile", "method": { - "fullName": "google.cloud.config.v1.Config.ExportDeploymentStatefile", + "fullName": "google.cloud.config.v1.Config.DeleteStatefile", "service": { "fullName": "google.cloud.config.v1.Config", "shortName": "Config" }, - "shortName": "ExportDeploymentStatefile" + "shortName": "DeleteStatefile" }, "parameters": [ { "name": "request", - "type": "google.cloud.config_v1.types.ExportDeploymentStatefileRequest" + "type": "google.cloud.config_v1.types.DeleteStatefileRequest" + }, + { + "name": "name", + "type": "str" }, { "name": "retry", @@ -615,22 +795,21 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.config_v1.types.Statefile", - "shortName": "export_deployment_statefile" + "shortName": "delete_statefile" }, - "description": "Sample for ExportDeploymentStatefile", - "file": "config_v1_generated_config_export_deployment_statefile_sync.py", + "description": "Sample for DeleteStatefile", + "file": "config_v1_generated_config_delete_statefile_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "config_v1_generated_Config_ExportDeploymentStatefile_sync", + "regionTag": "config_v1_generated_Config_DeleteStatefile_sync", "segments": [ { - "end": 51, + "end": 50, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 50, "start": 27, "type": "SHORT" }, @@ -640,18 +819,169 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "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, str]" + } + ], + "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, str]" + } + ], + "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" } ], @@ -667,21 +997,331 @@ }, "fullName": "google.cloud.config_v1.ConfigAsyncClient.export_lock_info", "method": { - "fullName": "google.cloud.config.v1.Config.ExportLockInfo", + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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, str]" + } + ], + "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": "ExportLockInfo" + "shortName": "ExportRevisionStatefile" }, "parameters": [ { "name": "request", - "type": "google.cloud.config_v1.types.ExportLockInfoRequest" - }, - { - "name": "name", - "type": "str" + "type": "google.cloud.config_v1.types.ExportRevisionStatefileRequest" }, { "name": "retry", @@ -696,14 +1336,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.config_v1.types.LockInfo", - "shortName": "export_lock_info" + "resultType": "google.cloud.config_v1.types.Statefile", + "shortName": "export_revision_statefile" }, - "description": "Sample for ExportLockInfo", - "file": "config_v1_generated_config_export_lock_info_async.py", + "description": "Sample for ExportRevisionStatefile", + "file": "config_v1_generated_config_export_revision_statefile_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "config_v1_generated_Config_ExportLockInfo_async", + "regionTag": "config_v1_generated_Config_ExportRevisionStatefile_async", "segments": [ { "end": 51, @@ -736,7 +1376,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "config_v1_generated_config_export_lock_info_async.py" + "title": "config_v1_generated_config_export_revision_statefile_async.py" }, { "canonical": true, @@ -745,23 +1385,19 @@ "fullName": "google.cloud.config_v1.ConfigClient", "shortName": "ConfigClient" }, - "fullName": "google.cloud.config_v1.ConfigClient.export_lock_info", + "fullName": "google.cloud.config_v1.ConfigClient.export_revision_statefile", "method": { - "fullName": "google.cloud.config.v1.Config.ExportLockInfo", + "fullName": "google.cloud.config.v1.Config.ExportRevisionStatefile", "service": { "fullName": "google.cloud.config.v1.Config", "shortName": "Config" }, - "shortName": "ExportLockInfo" + "shortName": "ExportRevisionStatefile" }, "parameters": [ { "name": "request", - "type": "google.cloud.config_v1.types.ExportLockInfoRequest" - }, - { - "name": "name", - "type": "str" + "type": "google.cloud.config_v1.types.ExportRevisionStatefileRequest" }, { "name": "retry", @@ -776,14 +1412,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.config_v1.types.LockInfo", - "shortName": "export_lock_info" + "resultType": "google.cloud.config_v1.types.Statefile", + "shortName": "export_revision_statefile" }, - "description": "Sample for ExportLockInfo", - "file": "config_v1_generated_config_export_lock_info_sync.py", + "description": "Sample for ExportRevisionStatefile", + "file": "config_v1_generated_config_export_revision_statefile_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "config_v1_generated_Config_ExportLockInfo_sync", + "regionTag": "config_v1_generated_Config_ExportRevisionStatefile_sync", "segments": [ { "end": 51, @@ -816,7 +1452,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "config_v1_generated_config_export_lock_info_sync.py" + "title": "config_v1_generated_config_export_revision_statefile_sync.py" }, { "canonical": true, @@ -826,19 +1462,23 @@ "fullName": "google.cloud.config_v1.ConfigAsyncClient", "shortName": "ConfigAsyncClient" }, - "fullName": "google.cloud.config_v1.ConfigAsyncClient.export_revision_statefile", + "fullName": "google.cloud.config_v1.ConfigAsyncClient.get_deployment", "method": { - "fullName": "google.cloud.config.v1.Config.ExportRevisionStatefile", + "fullName": "google.cloud.config.v1.Config.GetDeployment", "service": { "fullName": "google.cloud.config.v1.Config", "shortName": "Config" }, - "shortName": "ExportRevisionStatefile" + "shortName": "GetDeployment" }, "parameters": [ { "name": "request", - "type": "google.cloud.config_v1.types.ExportRevisionStatefileRequest" + "type": "google.cloud.config_v1.types.GetDeploymentRequest" + }, + { + "name": "name", + "type": "str" }, { "name": "retry", @@ -853,14 +1493,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.config_v1.types.Statefile", - "shortName": "export_revision_statefile" + "resultType": "google.cloud.config_v1.types.Deployment", + "shortName": "get_deployment" }, - "description": "Sample for ExportRevisionStatefile", - "file": "config_v1_generated_config_export_revision_statefile_async.py", + "description": "Sample for GetDeployment", + "file": "config_v1_generated_config_get_deployment_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "config_v1_generated_Config_ExportRevisionStatefile_async", + "regionTag": "config_v1_generated_Config_GetDeployment_async", "segments": [ { "end": 51, @@ -893,7 +1533,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "config_v1_generated_config_export_revision_statefile_async.py" + "title": "config_v1_generated_config_get_deployment_async.py" }, { "canonical": true, @@ -902,19 +1542,23 @@ "fullName": "google.cloud.config_v1.ConfigClient", "shortName": "ConfigClient" }, - "fullName": "google.cloud.config_v1.ConfigClient.export_revision_statefile", + "fullName": "google.cloud.config_v1.ConfigClient.get_deployment", "method": { - "fullName": "google.cloud.config.v1.Config.ExportRevisionStatefile", + "fullName": "google.cloud.config.v1.Config.GetDeployment", "service": { "fullName": "google.cloud.config.v1.Config", "shortName": "Config" }, - "shortName": "ExportRevisionStatefile" + "shortName": "GetDeployment" }, "parameters": [ { "name": "request", - "type": "google.cloud.config_v1.types.ExportRevisionStatefileRequest" + "type": "google.cloud.config_v1.types.GetDeploymentRequest" + }, + { + "name": "name", + "type": "str" }, { "name": "retry", @@ -929,14 +1573,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.config_v1.types.Statefile", - "shortName": "export_revision_statefile" + "resultType": "google.cloud.config_v1.types.Deployment", + "shortName": "get_deployment" }, - "description": "Sample for ExportRevisionStatefile", - "file": "config_v1_generated_config_export_revision_statefile_sync.py", + "description": "Sample for GetDeployment", + "file": "config_v1_generated_config_get_deployment_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "config_v1_generated_Config_ExportRevisionStatefile_sync", + "regionTag": "config_v1_generated_Config_GetDeployment_sync", "segments": [ { "end": 51, @@ -969,7 +1613,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "config_v1_generated_config_export_revision_statefile_sync.py" + "title": "config_v1_generated_config_get_deployment_sync.py" }, { "canonical": true, @@ -979,19 +1623,19 @@ "fullName": "google.cloud.config_v1.ConfigAsyncClient", "shortName": "ConfigAsyncClient" }, - "fullName": "google.cloud.config_v1.ConfigAsyncClient.get_deployment", + "fullName": "google.cloud.config_v1.ConfigAsyncClient.get_preview", "method": { - "fullName": "google.cloud.config.v1.Config.GetDeployment", + "fullName": "google.cloud.config.v1.Config.GetPreview", "service": { "fullName": "google.cloud.config.v1.Config", "shortName": "Config" }, - "shortName": "GetDeployment" + "shortName": "GetPreview" }, "parameters": [ { "name": "request", - "type": "google.cloud.config_v1.types.GetDeploymentRequest" + "type": "google.cloud.config_v1.types.GetPreviewRequest" }, { "name": "name", @@ -1010,14 +1654,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.config_v1.types.Deployment", - "shortName": "get_deployment" + "resultType": "google.cloud.config_v1.types.Preview", + "shortName": "get_preview" }, - "description": "Sample for GetDeployment", - "file": "config_v1_generated_config_get_deployment_async.py", + "description": "Sample for GetPreview", + "file": "config_v1_generated_config_get_preview_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "config_v1_generated_Config_GetDeployment_async", + "regionTag": "config_v1_generated_Config_GetPreview_async", "segments": [ { "end": 51, @@ -1050,7 +1694,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "config_v1_generated_config_get_deployment_async.py" + "title": "config_v1_generated_config_get_preview_async.py" }, { "canonical": true, @@ -1059,19 +1703,19 @@ "fullName": "google.cloud.config_v1.ConfigClient", "shortName": "ConfigClient" }, - "fullName": "google.cloud.config_v1.ConfigClient.get_deployment", + "fullName": "google.cloud.config_v1.ConfigClient.get_preview", "method": { - "fullName": "google.cloud.config.v1.Config.GetDeployment", + "fullName": "google.cloud.config.v1.Config.GetPreview", "service": { "fullName": "google.cloud.config.v1.Config", "shortName": "Config" }, - "shortName": "GetDeployment" + "shortName": "GetPreview" }, "parameters": [ { "name": "request", - "type": "google.cloud.config_v1.types.GetDeploymentRequest" + "type": "google.cloud.config_v1.types.GetPreviewRequest" }, { "name": "name", @@ -1090,14 +1734,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.config_v1.types.Deployment", - "shortName": "get_deployment" + "resultType": "google.cloud.config_v1.types.Preview", + "shortName": "get_preview" }, - "description": "Sample for GetDeployment", - "file": "config_v1_generated_config_get_deployment_sync.py", + "description": "Sample for GetPreview", + "file": "config_v1_generated_config_get_preview_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "config_v1_generated_Config_GetDeployment_sync", + "regionTag": "config_v1_generated_Config_GetPreview_sync", "segments": [ { "end": 51, @@ -1130,7 +1774,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "config_v1_generated_config_get_deployment_sync.py" + "title": "config_v1_generated_config_get_preview_sync.py" }, { "canonical": true, @@ -1784,6 +2428,167 @@ ], "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, str]" + } + ], + "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, str]" + } + ], + "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": { diff --git a/packages/google-cloud-config/scripts/fixup_config_v1_keywords.py b/packages/google-cloud-config/scripts/fixup_config_v1_keywords.py index 8d7b0d1d739f..c9978014e855 100644 --- a/packages/google-cloud-config/scripts/fixup_config_v1_keywords.py +++ b/packages/google-cloud-config/scripts/fixup_config_v1_keywords.py @@ -40,16 +40,21 @@ 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_revision': ('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_resources': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), 'list_revisions': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), 'lock_deployment': ('name', ), 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 635b310aed98..e4be71f0f933 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 @@ -5024,6 +5024,1336 @@ async def test_export_lock_info_flattened_error_async(): ) +@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] + assert args[0] == config.CreatePreviewRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_preview_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_preview), "__call__") as call: + client.create_preview() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == config.CreatePreviewRequest() + + +@pytest.mark.asyncio +async def test_create_preview_async( + transport: str = "grpc_asyncio", request_type=config.CreatePreviewRequest +): + client = ConfigAsyncClient( + 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 = 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] + assert args[0] == config.CreatePreviewRequest() + + # 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=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 = 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=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.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=ga_credentials.AnonymousCredentials(), + ) + + # 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", + ) + 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] + assert args[0] == config.GetPreviewRequest() + + # 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" + + +def test_get_preview_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_preview), "__call__") as call: + client.get_preview() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == config.GetPreviewRequest() + + +@pytest.mark.asyncio +async def test_get_preview_async( + transport: str = "grpc_asyncio", request_type=config.GetPreviewRequest +): + client = ConfigAsyncClient( + 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 = 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", + ) + ) + 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] + assert args[0] == config.GetPreviewRequest() + + # 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" + + +@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=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 = 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=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.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=ga_credentials.AnonymousCredentials(), + ) + + # 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] + assert args[0] == config.ListPreviewsRequest() + + # 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_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_previews), "__call__") as call: + client.list_previews() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == config.ListPreviewsRequest() + + +@pytest.mark.asyncio +async def test_list_previews_async( + transport: str = "grpc_asyncio", request_type=config.ListPreviewsRequest +): + client = ConfigAsyncClient( + 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 = 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] + assert args[0] == config.ListPreviewsRequest() + + # 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=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 = 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=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.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=ga_credentials.AnonymousCredentials(), + ) + + # 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, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_previews(request={}) + + assert pager._metadata == metadata + + 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=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__", 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=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__", 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] + assert args[0] == config.DeletePreviewRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_preview_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_preview), "__call__") as call: + client.delete_preview() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == config.DeletePreviewRequest() + + +@pytest.mark.asyncio +async def test_delete_preview_async( + transport: str = "grpc_asyncio", request_type=config.DeletePreviewRequest +): + client = ConfigAsyncClient( + 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 = 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] + assert args[0] == config.DeletePreviewRequest() + + # 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=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 = 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=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.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=ga_credentials.AnonymousCredentials(), + ) + + # 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] + assert args[0] == config.ExportPreviewResultRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, config.ExportPreviewResultResponse) + + +def test_export_preview_result_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # 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: + client.export_preview_result() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == config.ExportPreviewResultRequest() + + +@pytest.mark.asyncio +async def test_export_preview_result_async( + transport: str = "grpc_asyncio", request_type=config.ExportPreviewResultRequest +): + client = ConfigAsyncClient( + 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 = 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] + assert args[0] == config.ExportPreviewResultRequest() + + # 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=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 = 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", [ @@ -5031,20 +6361,1756 @@ async def test_export_lock_info_flattened_error_async(): dict, ], ) -def test_list_deployments_rest(request_type): +def test_list_deployments_rest(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 = 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 + 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"] + + +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, + including_default_value_fields=False, + 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 + + 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",)) + ) + + +@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, "pre_list_deployments" + ) as pre: + pre.assert_not_called() + post.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 = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = config.ListDeploymentsResponse.to_json( + config.ListDeploymentsResponse() + ) + + request = config.ListDeploymentsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = config.ListDeploymentsResponse() + + client.list_deployments( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_deployments_rest_bad_request( + transport: str = "rest", request_type=config.ListDeploymentsRequest +): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_deployments(request) + + +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 + + 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 + + +@pytest.mark.parametrize( + "request_type", + [ + config.GetDeploymentRequest, + dict, + ], +) +def test_get_deployment_rest(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, + ) + + # 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 + 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 + + +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, + including_default_value_fields=False, + 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 + + 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",))) + + +@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, "pre_get_deployment" + ) as pre: + pre.assert_not_called() + post.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 = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = config.Deployment.to_json(config.Deployment()) + + request = config.GetDeploymentRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = config.Deployment() + + client.get_deployment( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_deployment_rest_bad_request( + transport: str = "rest", request_type=config.GetDeploymentRequest +): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_deployment(request) + + +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 + + 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_get_deployment_rest_error(): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + config.CreateDeploymentRequest, + dict, + ], +) +def test_create_deployment_rest(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, + } + # 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 = 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 + response = client.create_deployment(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +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, + including_default_value_fields=False, + 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 + + 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", + ) + ) + ) + + +@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, "pre_create_deployment" + ) as pre: + pre.assert_not_called() + post.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 = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = config.CreateDeploymentRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_deployment( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_deployment_rest_bad_request( + transport: str = "rest", request_type=config.CreateDeploymentRequest +): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_deployment(request) + + +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 + + 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_create_deployment_rest_error(): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + config.UpdateDeploymentRequest, + dict, + ], +) +def test_update_deployment_rest(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, + } + # 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 = 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 + response = client.update_deployment(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +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, + including_default_value_fields=False, + 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 + + 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",)) + ) + + +@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, "pre_update_deployment" + ) as pre: + pre.assert_not_called() + post.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 = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = config.UpdateDeploymentRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_deployment( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_deployment_rest_bad_request( + transport: str = "rest", request_type=config.UpdateDeploymentRequest +): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_deployment(request) + + +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 + + 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_update_deployment_rest_error(): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + config.DeleteDeploymentRequest, + dict, + ], +) +def test_delete_deployment_rest(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 = 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 + response = client.delete_deployment(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +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, + including_default_value_fields=False, + 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 + + 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",)) + ) + + +@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, "pre_delete_deployment" + ) as pre: + pre.assert_not_called() + post.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 = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = config.DeleteDeploymentRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_deployment( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_deployment_rest_bad_request( + transport: str = "rest", request_type=config.DeleteDeploymentRequest +): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # 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 = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_deployment(request) + + +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 + + 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_delete_deployment_rest_error(): + client = ConfigClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + config.ListRevisionsRequest, + dict, + ], +) +def test_list_revisions_rest(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 = {"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.ListDeploymentsResponse( + return_value = config.ListRevisionsResponse( next_page_token="next_page_token_value", unreachable=["unreachable_value"], ) @@ -5053,22 +8119,20 @@ def test_list_deployments_rest(request_type): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = config.ListDeploymentsResponse.pb(return_value) + 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 - response = client.list_deployments(request) + response = client.list_revisions(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListDeploymentsPager) + assert isinstance(response, pagers.ListRevisionsPager) assert response.next_page_token == "next_page_token_value" assert response.unreachable == ["unreachable_value"] -def test_list_deployments_rest_required_fields( - request_type=config.ListDeploymentsRequest, -): +def test_list_revisions_rest_required_fields(request_type=config.ListRevisionsRequest): transport_class = transports.ConfigRestTransport request_init = {} @@ -5087,7 +8151,7 @@ def test_list_deployments_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_deployments._get_unset_required_fields(jsonified_request) + ).list_revisions._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -5096,7 +8160,7 @@ def test_list_deployments_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_deployments._get_unset_required_fields(jsonified_request) + ).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( ( @@ -5119,7 +8183,7 @@ def test_list_deployments_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = config.ListDeploymentsResponse() + 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 @@ -5140,25 +8204,25 @@ def test_list_deployments_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = config.ListDeploymentsResponse.pb(return_value) + 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 - response = client.list_deployments(request) + 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_deployments_rest_unset_required_fields(): +def test_list_revisions_rest_unset_required_fields(): transport = transports.ConfigRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.list_deployments._get_unset_required_fields({}) + unset_fields = transport.list_revisions._get_unset_required_fields({}) assert set(unset_fields) == ( set( ( @@ -5173,7 +8237,7 @@ def test_list_deployments_rest_unset_required_fields(): @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_deployments_rest_interceptors(null_interceptor): +def test_list_revisions_rest_interceptors(null_interceptor): transport = transports.ConfigRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.ConfigRestInterceptor(), @@ -5184,13 +8248,13 @@ def test_list_deployments_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.ConfigRestInterceptor, "post_list_deployments" + transports.ConfigRestInterceptor, "post_list_revisions" ) as post, mock.patch.object( - transports.ConfigRestInterceptor, "pre_list_deployments" + transports.ConfigRestInterceptor, "pre_list_revisions" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = config.ListDeploymentsRequest.pb(config.ListDeploymentsRequest()) + pb_message = config.ListRevisionsRequest.pb(config.ListRevisionsRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -5201,19 +8265,19 @@ def test_list_deployments_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = config.ListDeploymentsResponse.to_json( - config.ListDeploymentsResponse() + req.return_value._content = config.ListRevisionsResponse.to_json( + config.ListRevisionsResponse() ) - request = config.ListDeploymentsRequest() + request = config.ListRevisionsRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = config.ListDeploymentsResponse() + post.return_value = config.ListRevisionsResponse() - client.list_deployments( + client.list_revisions( request, metadata=[ ("key", "val"), @@ -5225,8 +8289,8 @@ def test_list_deployments_rest_interceptors(null_interceptor): post.assert_called_once() -def test_list_deployments_rest_bad_request( - transport: str = "rest", request_type=config.ListDeploymentsRequest +def test_list_revisions_rest_bad_request( + transport: str = "rest", request_type=config.ListRevisionsRequest ): client = ConfigClient( credentials=ga_credentials.AnonymousCredentials(), @@ -5234,7 +8298,7 @@ def test_list_deployments_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} + 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. @@ -5246,10 +8310,10 @@ def test_list_deployments_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.list_deployments(request) + client.list_revisions(request) -def test_list_deployments_rest_flattened(): +def test_list_revisions_rest_flattened(): client = ConfigClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -5258,10 +8322,12 @@ def test_list_deployments_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = config.ListDeploymentsResponse() + return_value = config.ListRevisionsResponse() # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/locations/sample2"} + sample_request = { + "parent": "projects/sample1/locations/sample2/deployments/sample3" + } # get truthy value for each flattened field mock_args = dict( @@ -5273,25 +8339,25 @@ def test_list_deployments_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = config.ListDeploymentsResponse.pb(return_value) + 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 - client.list_deployments(**mock_args) + 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" + "%s/v1/{parent=projects/*/locations/*/deployments/*}/revisions" % client.transport._host, args[1], ) -def test_list_deployments_rest_flattened_error(transport: str = "rest"): +def test_list_revisions_rest_flattened_error(transport: str = "rest"): client = ConfigClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -5300,13 +8366,13 @@ def test_list_deployments_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_deployments( - config.ListDeploymentsRequest(), + client.list_revisions( + config.ListRevisionsRequest(), parent="parent_value", ) -def test_list_deployments_rest_pager(transport: str = "rest"): +def test_list_revisions_rest_pager(transport: str = "rest"): client = ConfigClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -5318,28 +8384,28 @@ def test_list_deployments_rest_pager(transport: str = "rest"): # 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(), + config.ListRevisionsResponse( + revisions=[ + config.Revision(), + config.Revision(), + config.Revision(), ], next_page_token="abc", ), - config.ListDeploymentsResponse( - deployments=[], + config.ListRevisionsResponse( + revisions=[], next_page_token="def", ), - config.ListDeploymentsResponse( - deployments=[ - config.Deployment(), + config.ListRevisionsResponse( + revisions=[ + config.Revision(), ], next_page_token="ghi", ), - config.ListDeploymentsResponse( - deployments=[ - config.Deployment(), - config.Deployment(), + config.ListRevisionsResponse( + revisions=[ + config.Revision(), + config.Revision(), ], ), ) @@ -5347,22 +8413,24 @@ def test_list_deployments_rest_pager(transport: str = "rest"): response = response + response # Wrap the values into proper Response objs - response = tuple(config.ListDeploymentsResponse.to_json(x) for x in response) + 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"} + sample_request = { + "parent": "projects/sample1/locations/sample2/deployments/sample3" + } - pager = client.list_deployments(request=sample_request) + pager = client.list_revisions(request=sample_request) results = list(pager) assert len(results) == 6 - assert all(isinstance(i, config.Deployment) for i in results) + assert all(isinstance(i, config.Revision) for i in results) - pages = list(client.list_deployments(request=sample_request).pages) + 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 @@ -5370,68 +8438,68 @@ def test_list_deployments_rest_pager(transport: str = "rest"): @pytest.mark.parametrize( "request_type", [ - config.GetDeploymentRequest, + config.GetRevisionRequest, dict, ], ) -def test_get_deployment_rest(request_type): +def test_get_revision_rest(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_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.Deployment( + return_value = config.Revision( name="name_value", - state=config.Deployment.State.CREATING, - latest_revision="latest_revision_value", + action=config.Revision.Action.CREATE, + state=config.Revision.State.APPLYING, state_detail="state_detail_value", - error_code=config.Deployment.ErrorCode.REVISION_FAILED, - delete_build="delete_build_value", - delete_logs="delete_logs_value", + error_code=config.Revision.ErrorCode.CLOUD_BUILD_PERMISSION_DENIED, + build="build_value", + logs="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, ) # 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) + 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 - response = client.get_deployment(request) + response = client.get_revision(request) # Establish that the response is the type that we expect. - assert isinstance(response, config.Deployment) + assert isinstance(response, config.Revision) assert response.name == "name_value" - assert response.state == config.Deployment.State.CREATING - assert response.latest_revision == "latest_revision_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.Deployment.ErrorCode.REVISION_FAILED - assert response.delete_build == "delete_build_value" - assert response.delete_logs == "delete_logs_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.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 -def test_get_deployment_rest_required_fields(request_type=config.GetDeploymentRequest): +def test_get_revision_rest_required_fields(request_type=config.GetRevisionRequest): transport_class = transports.ConfigRestTransport request_init = {} @@ -5450,7 +8518,7 @@ def test_get_deployment_rest_required_fields(request_type=config.GetDeploymentRe unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_deployment._get_unset_required_fields(jsonified_request) + ).get_revision._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -5459,7 +8527,7 @@ def test_get_deployment_rest_required_fields(request_type=config.GetDeploymentRe unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_deployment._get_unset_required_fields(jsonified_request) + ).get_revision._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -5473,7 +8541,7 @@ def test_get_deployment_rest_required_fields(request_type=config.GetDeploymentRe request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = config.Deployment() + 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 @@ -5494,30 +8562,30 @@ def test_get_deployment_rest_required_fields(request_type=config.GetDeploymentRe response_value.status_code = 200 # Convert return value to protobuf type - return_value = config.Deployment.pb(return_value) + 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 - response = client.get_deployment(request) + 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_deployment_rest_unset_required_fields(): +def test_get_revision_rest_unset_required_fields(): transport = transports.ConfigRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.get_deployment._get_unset_required_fields({}) + unset_fields = transport.get_revision._get_unset_required_fields({}) assert set(unset_fields) == (set(()) & set(("name",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_deployment_rest_interceptors(null_interceptor): +def test_get_revision_rest_interceptors(null_interceptor): transport = transports.ConfigRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.ConfigRestInterceptor(), @@ -5528,13 +8596,13 @@ def test_get_deployment_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.ConfigRestInterceptor, "post_get_deployment" + transports.ConfigRestInterceptor, "post_get_revision" ) as post, mock.patch.object( - transports.ConfigRestInterceptor, "pre_get_deployment" + transports.ConfigRestInterceptor, "pre_get_revision" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = config.GetDeploymentRequest.pb(config.GetDeploymentRequest()) + pb_message = config.GetRevisionRequest.pb(config.GetRevisionRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -5545,17 +8613,17 @@ def test_get_deployment_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = config.Deployment.to_json(config.Deployment()) + req.return_value._content = config.Revision.to_json(config.Revision()) - request = config.GetDeploymentRequest() + request = config.GetRevisionRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = config.Deployment() + post.return_value = config.Revision() - client.get_deployment( + client.get_revision( request, metadata=[ ("key", "val"), @@ -5567,8 +8635,8 @@ def test_get_deployment_rest_interceptors(null_interceptor): post.assert_called_once() -def test_get_deployment_rest_bad_request( - transport: str = "rest", request_type=config.GetDeploymentRequest +def test_get_revision_rest_bad_request( + transport: str = "rest", request_type=config.GetRevisionRequest ): client = ConfigClient( credentials=ga_credentials.AnonymousCredentials(), @@ -5576,7 +8644,9 @@ def test_get_deployment_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/deployments/sample3"} + 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. @@ -5588,10 +8658,10 @@ def test_get_deployment_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.get_deployment(request) + client.get_revision(request) -def test_get_deployment_rest_flattened(): +def test_get_revision_rest_flattened(): client = ConfigClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -5600,11 +8670,11 @@ def test_get_deployment_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = config.Deployment() + return_value = config.Revision() # get arguments that satisfy an http rule for this method sample_request = { - "name": "projects/sample1/locations/sample2/deployments/sample3" + "name": "projects/sample1/locations/sample2/deployments/sample3/revisions/sample4" } # get truthy value for each flattened field @@ -5617,25 +8687,25 @@ def test_get_deployment_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = config.Deployment.pb(return_value) + 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 - client.get_deployment(**mock_args) + 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/*}" + "%s/v1/{name=projects/*/locations/*/deployments/*/revisions/*}" % client.transport._host, args[1], ) -def test_get_deployment_rest_flattened_error(transport: str = "rest"): +def test_get_revision_rest_flattened_error(transport: str = "rest"): client = ConfigClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -5644,13 +8714,13 @@ def test_get_deployment_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_deployment( - config.GetDeploymentRequest(), + client.get_revision( + config.GetRevisionRequest(), name="name_value", ) -def test_get_deployment_rest_error(): +def test_get_revision_rest_error(): client = ConfigClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -5659,162 +8729,54 @@ def test_get_deployment_rest_error(): @pytest.mark.parametrize( "request_type", [ - config.CreateDeploymentRequest, + config.GetResourceRequest, dict, ], ) -def test_create_deployment_rest(request_type): +def test_get_resource_rest(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, + request_init = { + "name": "projects/sample1/locations/sample2/deployments/sample3/revisions/sample4/resources/sample5" } - # 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") + 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 = 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 - response = client.create_deployment(request) + response = client.get_resource(request) # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" + 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_create_deployment_rest_required_fields( - request_type=config.CreateDeploymentRequest, -): +def test_get_resource_rest_required_fields(request_type=config.GetResourceRequest): transport_class = transports.ConfigRestTransport request_init = {} - request_init["parent"] = "" - request_init["deployment_id"] = "" + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -5826,37 +8788,24 @@ def test_create_deployment_rest_required_fields( ) # 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) + ).get_resource._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" + jsonified_request["name"] = "name_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", - ) - ) + ).get_resource._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 "deploymentId" in jsonified_request - assert jsonified_request["deploymentId"] == "deployment_id_value" + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = ConfigClient( credentials=ga_credentials.AnonymousCredentials(), @@ -5865,7 +8814,7 @@ def test_create_deployment_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = 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 @@ -5877,57 +8826,39 @@ def test_create_deployment_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "get", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 + + # 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 - response = client.create_deployment(request) + response = client.get_resource(request) - expected_params = [ - ( - "deploymentId", - "", - ), - ("$alt", "json;enum-encoding=int"), - ] + expected_params = [("$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(): +def test_get_resource_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", - ) - ) - ) + unset_fields = transport.get_resource._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_deployment_rest_interceptors(null_interceptor): +def test_get_resource_rest_interceptors(null_interceptor): transport = transports.ConfigRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.ConfigRestInterceptor(), @@ -5938,15 +8869,13 @@ def test_create_deployment_rest_interceptors(null_interceptor): ) 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" + transports.ConfigRestInterceptor, "post_get_resource" ) as post, mock.patch.object( - transports.ConfigRestInterceptor, "pre_create_deployment" + transports.ConfigRestInterceptor, "pre_get_resource" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = config.CreateDeploymentRequest.pb(config.CreateDeploymentRequest()) + pb_message = config.GetResourceRequest.pb(config.GetResourceRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -5957,19 +8886,17 @@ def test_create_deployment_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson( - operations_pb2.Operation() - ) + req.return_value._content = config.Resource.to_json(config.Resource()) - request = config.CreateDeploymentRequest() + request = config.GetResourceRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() + post.return_value = config.Resource() - client.create_deployment( + client.get_resource( request, metadata=[ ("key", "val"), @@ -5981,8 +8908,8 @@ def test_create_deployment_rest_interceptors(null_interceptor): post.assert_called_once() -def test_create_deployment_rest_bad_request( - transport: str = "rest", request_type=config.CreateDeploymentRequest +def test_get_resource_rest_bad_request( + transport: str = "rest", request_type=config.GetResourceRequest ): client = ConfigClient( credentials=ga_credentials.AnonymousCredentials(), @@ -5990,7 +8917,9 @@ def test_create_deployment_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} + 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. @@ -6002,10 +8931,10 @@ def test_create_deployment_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.create_deployment(request) + client.get_resource(request) -def test_create_deployment_rest_flattened(): +def test_get_resource_rest_flattened(): client = ConfigClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -6014,44 +8943,42 @@ def test_create_deployment_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = config.Resource() # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/locations/sample2"} + sample_request = { + "name": "projects/sample1/locations/sample2/deployments/sample3/revisions/sample4/resources/sample5" + } # 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", + 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 - client.create_deployment(**mock_args) + 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/{parent=projects/*/locations/*}/deployments" + "%s/v1/{name=projects/*/locations/*/deployments/*/revisions/*/resources/*}" % client.transport._host, args[1], ) -def test_create_deployment_rest_flattened_error(transport: str = "rest"): +def test_get_resource_rest_flattened_error(transport: str = "rest"): client = ConfigClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -6060,19 +8987,13 @@ def test_create_deployment_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.create_deployment( - config.CreateDeploymentRequest(), - parent="parent_value", - deployment=config.Deployment( - terraform_blueprint=config.TerraformBlueprint( - gcs_source="gcs_source_value" - ) - ), - deployment_id="deployment_id_value", + client.get_resource( + config.GetResourceRequest(), + name="name_value", ) -def test_create_deployment_rest_error(): +def test_get_resource_rest_error(): client = ConfigClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -6081,11 +9002,11 @@ def test_create_deployment_rest_error(): @pytest.mark.parametrize( "request_type", [ - config.UpdateDeploymentRequest, + config.ListResourcesRequest, dict, ], ) -def test_update_deployment_rest(request_type): +def test_list_resources_rest(request_type): client = ConfigClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -6093,150 +9014,40 @@ def test_update_deployment_rest(request_type): # 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, + "parent": "projects/sample1/locations/sample2/deployments/sample3/revisions/sample4" } - # 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") + return_value = config.ListResourcesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) # 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 - response = client.update_deployment(request) + response = client.list_resources(request) # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" + assert isinstance(response, pagers.ListResourcesPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] -def test_update_deployment_rest_required_fields( - request_type=config.UpdateDeploymentRequest, -): +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( @@ -6251,24 +9062,30 @@ def test_update_deployment_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_deployment._get_unset_required_fields(jsonified_request) + ).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() - ).update_deployment._get_unset_required_fields(jsonified_request) + ).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( ( - "request_id", - "update_mask", + "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(), @@ -6277,7 +9094,7 @@ def test_update_deployment_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = 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 @@ -6289,45 +9106,49 @@ def test_update_deployment_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "patch", + "method": "get", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = 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 - response = client.update_deployment(request) + 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_update_deployment_rest_unset_required_fields(): +def test_list_resources_rest_unset_required_fields(): transport = transports.ConfigRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.update_deployment._get_unset_required_fields({}) + unset_fields = transport.list_resources._get_unset_required_fields({}) assert set(unset_fields) == ( set( ( - "requestId", - "updateMask", + "filter", + "orderBy", + "pageSize", + "pageToken", ) ) - & set(("deployment",)) + & set(("parent",)) ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_deployment_rest_interceptors(null_interceptor): +def test_list_resources_rest_interceptors(null_interceptor): transport = transports.ConfigRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.ConfigRestInterceptor(), @@ -6338,15 +9159,13 @@ def test_update_deployment_rest_interceptors(null_interceptor): ) 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" + transports.ConfigRestInterceptor, "post_list_resources" ) as post, mock.patch.object( - transports.ConfigRestInterceptor, "pre_update_deployment" + transports.ConfigRestInterceptor, "pre_list_resources" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = config.UpdateDeploymentRequest.pb(config.UpdateDeploymentRequest()) + pb_message = config.ListResourcesRequest.pb(config.ListResourcesRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -6357,19 +9176,19 @@ def test_update_deployment_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson( - operations_pb2.Operation() + req.return_value._content = config.ListResourcesResponse.to_json( + config.ListResourcesResponse() ) - request = config.UpdateDeploymentRequest() + request = config.ListResourcesRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() + post.return_value = config.ListResourcesResponse() - client.update_deployment( + client.list_resources( request, metadata=[ ("key", "val"), @@ -6381,8 +9200,8 @@ def test_update_deployment_rest_interceptors(null_interceptor): post.assert_called_once() -def test_update_deployment_rest_bad_request( - transport: str = "rest", request_type=config.UpdateDeploymentRequest +def test_list_resources_rest_bad_request( + transport: str = "rest", request_type=config.ListResourcesRequest ): client = ConfigClient( credentials=ga_credentials.AnonymousCredentials(), @@ -6391,7 +9210,7 @@ def test_update_deployment_rest_bad_request( # send a request that will satisfy transcoding request_init = { - "deployment": {"name": "projects/sample1/locations/sample2/deployments/sample3"} + "parent": "projects/sample1/locations/sample2/deployments/sample3/revisions/sample4" } request = request_type(**request_init) @@ -6404,10 +9223,10 @@ def test_update_deployment_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.update_deployment(request) + client.list_resources(request) -def test_update_deployment_rest_flattened(): +def test_list_resources_rest_flattened(): client = ConfigClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -6416,47 +9235,42 @@ def test_update_deployment_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = config.ListResourcesResponse() # get arguments that satisfy an http rule for this method sample_request = { - "deployment": { - "name": "projects/sample1/locations/sample2/deployments/sample3" - } + "parent": "projects/sample1/locations/sample2/deployments/sample3/revisions/sample4" } # 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"]), + 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 - client.update_deployment(**mock_args) + 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/{deployment.name=projects/*/locations/*/deployments/*}" + "%s/v1/{parent=projects/*/locations/*/deployments/*/revisions/*}/resources" % client.transport._host, args[1], ) -def test_update_deployment_rest_flattened_error(transport: str = "rest"): +def test_list_resources_rest_flattened_error(transport: str = "rest"): client = ConfigClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -6465,65 +9279,122 @@ def test_update_deployment_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.update_deployment( - config.UpdateDeploymentRequest(), - deployment=config.Deployment( - terraform_blueprint=config.TerraformBlueprint( - gcs_source="gcs_source_value" - ) - ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.list_resources( + config.ListResourcesRequest(), + parent="parent_value", ) -def test_update_deployment_rest_error(): +def test_list_resources_rest_pager(transport: str = "rest"): client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + 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 + @pytest.mark.parametrize( "request_type", [ - config.DeleteDeploymentRequest, + config.ExportDeploymentStatefileRequest, dict, ], ) -def test_delete_deployment_rest(request_type): +def test_export_deployment_statefile_rest(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_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 = operations_pb2.Operation(name="operations/spam") + return_value = config.Statefile( + signed_uri="signed_uri_value", + ) # 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 - response = client.delete_deployment(request) + response = client.export_deployment_statefile(request) # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" + assert isinstance(response, config.Statefile) + assert response.signed_uri == "signed_uri_value" -def test_delete_deployment_rest_required_fields( - request_type=config.DeleteDeploymentRequest, +def test_export_deployment_statefile_rest_required_fields( + request_type=config.ExportDeploymentStatefileRequest, ): transport_class = transports.ConfigRestTransport request_init = {} - request_init["name"] = "" + request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -6538,29 +9409,21 @@ def test_delete_deployment_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_deployment._get_unset_required_fields(jsonified_request) + ).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["name"] = "name_value" + jsonified_request["parent"] = "parent_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", - ) - ) + ).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 "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" client = ConfigClient( credentials=ga_credentials.AnonymousCredentials(), @@ -6569,7 +9432,7 @@ def test_delete_deployment_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = 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 @@ -6581,45 +9444,40 @@ def test_delete_deployment_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "delete", + "method": "post", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 + + # 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 - response = client.delete_deployment(request) + 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_delete_deployment_rest_unset_required_fields(): +def test_export_deployment_statefile_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",)) - ) + unset_fields = transport.export_deployment_statefile._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_deployment_rest_interceptors(null_interceptor): +def test_export_deployment_statefile_rest_interceptors(null_interceptor): transport = transports.ConfigRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.ConfigRestInterceptor(), @@ -6630,15 +9488,15 @@ def test_delete_deployment_rest_interceptors(null_interceptor): ) 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" + transports.ConfigRestInterceptor, "post_export_deployment_statefile" ) as post, mock.patch.object( - transports.ConfigRestInterceptor, "pre_delete_deployment" + transports.ConfigRestInterceptor, "pre_export_deployment_statefile" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = config.DeleteDeploymentRequest.pb(config.DeleteDeploymentRequest()) + pb_message = config.ExportDeploymentStatefileRequest.pb( + config.ExportDeploymentStatefileRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -6649,19 +9507,17 @@ def test_delete_deployment_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson( - operations_pb2.Operation() - ) + req.return_value._content = config.Statefile.to_json(config.Statefile()) - request = config.DeleteDeploymentRequest() + request = config.ExportDeploymentStatefileRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() + post.return_value = config.Statefile() - client.delete_deployment( + client.export_deployment_statefile( request, metadata=[ ("key", "val"), @@ -6673,8 +9529,8 @@ def test_delete_deployment_rest_interceptors(null_interceptor): post.assert_called_once() -def test_delete_deployment_rest_bad_request( - transport: str = "rest", request_type=config.DeleteDeploymentRequest +def test_export_deployment_statefile_rest_bad_request( + transport: str = "rest", request_type=config.ExportDeploymentStatefileRequest ): client = ConfigClient( credentials=ga_credentials.AnonymousCredentials(), @@ -6682,7 +9538,7 @@ def test_delete_deployment_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/deployments/sample3"} + 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. @@ -6694,67 +9550,10 @@ def test_delete_deployment_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.delete_deployment(request) - - -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 - - 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", - ) + client.export_deployment_statefile(request) -def test_delete_deployment_rest_error(): +def test_export_deployment_statefile_rest_error(): client = ConfigClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -6763,46 +9562,48 @@ def test_delete_deployment_rest_error(): @pytest.mark.parametrize( "request_type", [ - config.ListRevisionsRequest, + config.ExportRevisionStatefileRequest, dict, ], ) -def test_list_revisions_rest(request_type): +def test_export_revision_statefile_rest(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_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.ListRevisionsResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], + return_value = config.Statefile( + signed_uri="signed_uri_value", ) # 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) + 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 - response = client.list_revisions(request) + response = client.export_revision_statefile(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"] + assert isinstance(response, config.Statefile) + assert response.signed_uri == "signed_uri_value" -def test_list_revisions_rest_required_fields(request_type=config.ListRevisionsRequest): +def test_export_revision_statefile_rest_required_fields( + request_type=config.ExportRevisionStatefileRequest, +): transport_class = transports.ConfigRestTransport request_init = {} @@ -6821,7 +9622,7 @@ def test_list_revisions_rest_required_fields(request_type=config.ListRevisionsRe unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_revisions._get_unset_required_fields(jsonified_request) + ).export_revision_statefile._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -6830,16 +9631,7 @@ def test_list_revisions_rest_required_fields(request_type=config.ListRevisionsRe 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", - ) - ) + ).export_revision_statefile._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -6853,7 +9645,7 @@ def test_list_revisions_rest_required_fields(request_type=config.ListRevisionsRe request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = config.ListRevisionsResponse() + 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 @@ -6865,49 +9657,40 @@ def test_list_revisions_rest_required_fields(request_type=config.ListRevisionsRe pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "post", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = config.ListRevisionsResponse.pb(return_value) + 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 - response = client.list_revisions(request) + 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_list_revisions_rest_unset_required_fields(): +def test_export_revision_statefile_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",)) - ) + unset_fields = transport.export_revision_statefile._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_revisions_rest_interceptors(null_interceptor): +def test_export_revision_statefile_rest_interceptors(null_interceptor): transport = transports.ConfigRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.ConfigRestInterceptor(), @@ -6918,13 +9701,15 @@ def test_list_revisions_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.ConfigRestInterceptor, "post_list_revisions" + transports.ConfigRestInterceptor, "post_export_revision_statefile" ) as post, mock.patch.object( - transports.ConfigRestInterceptor, "pre_list_revisions" + transports.ConfigRestInterceptor, "pre_export_revision_statefile" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = config.ListRevisionsRequest.pb(config.ListRevisionsRequest()) + pb_message = config.ExportRevisionStatefileRequest.pb( + config.ExportRevisionStatefileRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -6935,19 +9720,17 @@ def test_list_revisions_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = config.ListRevisionsResponse.to_json( - config.ListRevisionsResponse() - ) + req.return_value._content = config.Statefile.to_json(config.Statefile()) - request = config.ListRevisionsRequest() + request = config.ExportRevisionStatefileRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = config.ListRevisionsResponse() + post.return_value = config.Statefile() - client.list_revisions( + client.export_revision_statefile( request, metadata=[ ("key", "val"), @@ -6959,8 +9742,8 @@ def test_list_revisions_rest_interceptors(null_interceptor): post.assert_called_once() -def test_list_revisions_rest_bad_request( - transport: str = "rest", request_type=config.ListRevisionsRequest +def test_export_revision_statefile_rest_bad_request( + transport: str = "rest", request_type=config.ExportRevisionStatefileRequest ): client = ConfigClient( credentials=ga_credentials.AnonymousCredentials(), @@ -6968,7 +9751,9 @@ def test_list_revisions_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/deployments/sample3"} + 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. @@ -6980,200 +9765,63 @@ def test_list_revisions_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.list_revisions(request) - - -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 - - 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", - ) + client.export_revision_statefile(request) -def test_list_revisions_rest_pager(transport: str = "rest"): +def test_export_revision_statefile_rest_error(): client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - # 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 - @pytest.mark.parametrize( "request_type", [ - config.GetRevisionRequest, + config.ImportStatefileRequest, dict, ], ) -def test_get_revision_rest(request_type): +def test_import_statefile_rest(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_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.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", + return_value = config.Statefile( + signed_uri="signed_uri_value", ) # 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) + 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 - response = client.get_revision(request) + response = client.import_statefile(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 isinstance(response, config.Statefile) + assert response.signed_uri == "signed_uri_value" -def test_get_revision_rest_required_fields(request_type=config.GetRevisionRequest): +def test_import_statefile_rest_required_fields( + request_type=config.ImportStatefileRequest, +): transport_class = transports.ConfigRestTransport request_init = {} - request_init["name"] = "" + request_init["parent"] = "" + request_init["lock_id"] = 0 request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -7188,21 +9836,24 @@ def test_get_revision_rest_required_fields(request_type=config.GetRevisionReques unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_revision._get_unset_required_fields(jsonified_request) + ).import_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["parent"] = "parent_value" + jsonified_request["lockId"] = 725 unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_revision._get_unset_required_fields(jsonified_request) + ).import_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 "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(), @@ -7211,7 +9862,7 @@ def test_get_revision_rest_required_fields(request_type=config.GetRevisionReques request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = config.Revision() + 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 @@ -7223,39 +9874,48 @@ def test_get_revision_rest_required_fields(request_type=config.GetRevisionReques pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "post", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = config.Revision.pb(return_value) + 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 - response = client.get_revision(request) + 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_get_revision_rest_unset_required_fields(): +def test_import_statefile_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",))) + unset_fields = transport.import_statefile._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "lockId", + ) + ) + ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_revision_rest_interceptors(null_interceptor): +def test_import_statefile_rest_interceptors(null_interceptor): transport = transports.ConfigRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.ConfigRestInterceptor(), @@ -7266,13 +9926,13 @@ def test_get_revision_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.ConfigRestInterceptor, "post_get_revision" + transports.ConfigRestInterceptor, "post_import_statefile" ) as post, mock.patch.object( - transports.ConfigRestInterceptor, "pre_get_revision" + transports.ConfigRestInterceptor, "pre_import_statefile" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = config.GetRevisionRequest.pb(config.GetRevisionRequest()) + pb_message = config.ImportStatefileRequest.pb(config.ImportStatefileRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -7283,17 +9943,17 @@ def test_get_revision_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = config.Revision.to_json(config.Revision()) + req.return_value._content = config.Statefile.to_json(config.Statefile()) - request = config.GetRevisionRequest() + request = config.ImportStatefileRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = config.Revision() + post.return_value = config.Statefile() - client.get_revision( + client.import_statefile( request, metadata=[ ("key", "val"), @@ -7305,8 +9965,8 @@ def test_get_revision_rest_interceptors(null_interceptor): post.assert_called_once() -def test_get_revision_rest_bad_request( - transport: str = "rest", request_type=config.GetRevisionRequest +def test_import_statefile_rest_bad_request( + transport: str = "rest", request_type=config.ImportStatefileRequest ): client = ConfigClient( credentials=ga_credentials.AnonymousCredentials(), @@ -7314,9 +9974,7 @@ def test_get_revision_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/deployments/sample3/revisions/sample4" - } + 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. @@ -7328,10 +9986,10 @@ def test_get_revision_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.get_revision(request) + client.import_statefile(request) -def test_get_revision_rest_flattened(): +def test_import_statefile_rest_flattened(): client = ConfigClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -7340,16 +9998,17 @@ def test_get_revision_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = config.Revision() + return_value = config.Statefile() # get arguments that satisfy an http rule for this method sample_request = { - "name": "projects/sample1/locations/sample2/deployments/sample3/revisions/sample4" + "parent": "projects/sample1/locations/sample2/deployments/sample3" } # get truthy value for each flattened field mock_args = dict( - name="name_value", + parent="parent_value", + lock_id=725, ) mock_args.update(sample_request) @@ -7357,25 +10016,25 @@ def test_get_revision_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = config.Revision.pb(return_value) + 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 - client.get_revision(**mock_args) + 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/{name=projects/*/locations/*/deployments/*/revisions/*}" + "%s/v1/{parent=projects/*/locations/*/deployments/*}:importState" % client.transport._host, args[1], ) -def test_get_revision_rest_flattened_error(transport: str = "rest"): +def test_import_statefile_rest_flattened_error(transport: str = "rest"): client = ConfigClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -7384,13 +10043,14 @@ def test_get_revision_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_revision( - config.GetRevisionRequest(), - name="name_value", + client.import_statefile( + config.ImportStatefileRequest(), + parent="parent_value", + lock_id=725, ) -def test_get_revision_rest_error(): +def test_import_statefile_rest_error(): client = ConfigClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -7399,54 +10059,46 @@ def test_get_revision_rest_error(): @pytest.mark.parametrize( "request_type", [ - config.GetResourceRequest, + config.DeleteStatefileRequest, dict, ], ) -def test_get_resource_rest(request_type): +def test_delete_statefile_rest(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_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.Resource( - name="name_value", - intent=config.Resource.Intent.CREATE, - state=config.Resource.State.PLANNED, - ) + return_value = None # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - # Convert return value to protobuf type - return_value = config.Resource.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "" response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_resource(request) + response = client.delete_statefile(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 + assert response is None -def test_get_resource_rest_required_fields(request_type=config.GetResourceRequest): +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( @@ -7461,21 +10113,24 @@ def test_get_resource_rest_required_fields(request_type=config.GetResourceReques unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_resource._get_unset_required_fields(jsonified_request) + ).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() - ).get_resource._get_unset_required_fields(jsonified_request) + ).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(), @@ -7484,7 +10139,7 @@ def test_get_resource_rest_required_fields(request_type=config.GetResourceReques request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = config.Resource() + 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 @@ -7496,39 +10151,45 @@ def test_get_resource_rest_required_fields(request_type=config.GetResourceReques pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "post", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = config.Resource.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "" response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_resource(request) + 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_get_resource_rest_unset_required_fields(): +def test_delete_statefile_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",))) + unset_fields = transport.delete_statefile._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "name", + "lockId", + ) + ) + ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_resource_rest_interceptors(null_interceptor): +def test_delete_statefile_rest_interceptors(null_interceptor): transport = transports.ConfigRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.ConfigRestInterceptor(), @@ -7539,13 +10200,10 @@ def test_get_resource_rest_interceptors(null_interceptor): ) 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, "pre_get_resource" + transports.ConfigRestInterceptor, "pre_delete_statefile" ) as pre: pre.assert_not_called() - post.assert_not_called() - pb_message = config.GetResourceRequest.pb(config.GetResourceRequest()) + pb_message = config.DeleteStatefileRequest.pb(config.DeleteStatefileRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -7556,17 +10214,15 @@ def test_get_resource_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = config.Resource.to_json(config.Resource()) - request = config.GetResourceRequest() + request = config.DeleteStatefileRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = config.Resource() - client.get_resource( + client.delete_statefile( request, metadata=[ ("key", "val"), @@ -7575,11 +10231,10 @@ def test_get_resource_rest_interceptors(null_interceptor): ) pre.assert_called_once() - post.assert_called_once() -def test_get_resource_rest_bad_request( - transport: str = "rest", request_type=config.GetResourceRequest +def test_delete_statefile_rest_bad_request( + transport: str = "rest", request_type=config.DeleteStatefileRequest ): client = ConfigClient( credentials=ga_credentials.AnonymousCredentials(), @@ -7587,9 +10242,7 @@ def test_get_resource_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/deployments/sample3/revisions/sample4/resources/sample5" - } + 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. @@ -7601,10 +10254,10 @@ def test_get_resource_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.get_resource(request) + client.delete_statefile(request) -def test_get_resource_rest_flattened(): +def test_delete_statefile_rest_flattened(): client = ConfigClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -7613,11 +10266,11 @@ def test_get_resource_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = config.Resource() + return_value = None # get arguments that satisfy an http rule for this method sample_request = { - "name": "projects/sample1/locations/sample2/deployments/sample3/revisions/sample4/resources/sample5" + "name": "projects/sample1/locations/sample2/deployments/sample3" } # get truthy value for each flattened field @@ -7629,26 +10282,24 @@ def test_get_resource_rest_flattened(): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - # Convert return value to protobuf type - return_value = config.Resource.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "" response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.get_resource(**mock_args) + 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/*/revisions/*/resources/*}" + "%s/v1/{name=projects/*/locations/*/deployments/*}:deleteState" % client.transport._host, args[1], ) -def test_get_resource_rest_flattened_error(transport: str = "rest"): +def test_delete_statefile_rest_flattened_error(transport: str = "rest"): client = ConfigClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -7657,13 +10308,13 @@ def test_get_resource_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_resource( - config.GetResourceRequest(), + client.delete_statefile( + config.DeleteStatefileRequest(), name="name_value", ) -def test_get_resource_rest_error(): +def test_delete_statefile_rest_error(): client = ConfigClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -7672,52 +10323,45 @@ def test_get_resource_rest_error(): @pytest.mark.parametrize( "request_type", [ - config.ListResourcesRequest, + config.LockDeploymentRequest, dict, ], ) -def test_list_resources_rest(request_type): +def test_lock_deployment_rest(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_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.ListResourcesResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) + return_value = operations_pb2.Operation(name="operations/spam") # 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 - response = client.list_resources(request) + response = client.lock_deployment(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"] + assert response.operation.name == "operations/spam" -def test_list_resources_rest_required_fields(request_type=config.ListResourcesRequest): +def test_lock_deployment_rest_required_fields( + request_type=config.LockDeploymentRequest, +): transport_class = transports.ConfigRestTransport request_init = {} - request_init["parent"] = "" + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -7732,30 +10376,21 @@ def test_list_resources_rest_required_fields(request_type=config.ListResourcesRe unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_resources._get_unset_required_fields(jsonified_request) + ).lock_deployment._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["name"] = "name_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", - ) - ) + ).lock_deployment._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 "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = ConfigClient( credentials=ga_credentials.AnonymousCredentials(), @@ -7764,7 +10399,7 @@ def test_list_resources_rest_required_fields(request_type=config.ListResourcesRe request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = config.ListResourcesResponse() + 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 @@ -7776,49 +10411,37 @@ def test_list_resources_rest_required_fields(request_type=config.ListResourcesRe pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "post", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = 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 - response = client.list_resources(request) + 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_list_resources_rest_unset_required_fields(): +def test_lock_deployment_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",)) - ) + unset_fields = transport.lock_deployment._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_resources_rest_interceptors(null_interceptor): +def test_lock_deployment_rest_interceptors(null_interceptor): transport = transports.ConfigRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.ConfigRestInterceptor(), @@ -7829,13 +10452,15 @@ def test_list_resources_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.ConfigRestInterceptor, "post_list_resources" + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.ConfigRestInterceptor, "post_lock_deployment" ) as post, mock.patch.object( - transports.ConfigRestInterceptor, "pre_list_resources" + transports.ConfigRestInterceptor, "pre_lock_deployment" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = config.ListResourcesRequest.pb(config.ListResourcesRequest()) + pb_message = config.LockDeploymentRequest.pb(config.LockDeploymentRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -7846,19 +10471,19 @@ def test_list_resources_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = config.ListResourcesResponse.to_json( - config.ListResourcesResponse() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() ) - request = config.ListResourcesRequest() + request = config.LockDeploymentRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = config.ListResourcesResponse() + post.return_value = operations_pb2.Operation() - client.list_resources( + client.lock_deployment( request, metadata=[ ("key", "val"), @@ -7870,8 +10495,8 @@ def test_list_resources_rest_interceptors(null_interceptor): post.assert_called_once() -def test_list_resources_rest_bad_request( - transport: str = "rest", request_type=config.ListResourcesRequest +def test_lock_deployment_rest_bad_request( + transport: str = "rest", request_type=config.LockDeploymentRequest ): client = ConfigClient( credentials=ga_credentials.AnonymousCredentials(), @@ -7879,9 +10504,7 @@ def test_list_resources_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = { - "parent": "projects/sample1/locations/sample2/deployments/sample3/revisions/sample4" - } + 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. @@ -7893,10 +10516,10 @@ def test_list_resources_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.list_resources(request) + client.lock_deployment(request) -def test_list_resources_rest_flattened(): +def test_lock_deployment_rest_flattened(): client = ConfigClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -7905,42 +10528,40 @@ def test_list_resources_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = config.ListResourcesResponse() + 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/deployments/sample3/revisions/sample4" + "name": "projects/sample1/locations/sample2/deployments/sample3" } # get truthy value for each flattened field mock_args = dict( - parent="parent_value", + name="name_value", ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - # Convert return value to protobuf type - return_value = 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 - client.list_resources(**mock_args) + 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/{parent=projects/*/locations/*/deployments/*/revisions/*}/resources" + "%s/v1/{name=projects/*/locations/*/deployments/*}:lock" % client.transport._host, args[1], ) -def test_list_resources_rest_flattened_error(transport: str = "rest"): +def test_lock_deployment_rest_flattened_error(transport: str = "rest"): client = ConfigClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -7949,122 +10570,61 @@ def test_list_resources_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_resources( - config.ListResourcesRequest(), - parent="parent_value", + client.lock_deployment( + config.LockDeploymentRequest(), + name="name_value", ) -def test_list_resources_rest_pager(transport: str = "rest"): +def test_lock_deployment_rest_error(): client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - # 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 - @pytest.mark.parametrize( "request_type", [ - config.ExportDeploymentStatefileRequest, + config.UnlockDeploymentRequest, dict, ], ) -def test_export_deployment_statefile_rest(request_type): +def test_unlock_deployment_rest(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_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.Statefile( - signed_uri="signed_uri_value", - ) + return_value = operations_pb2.Operation(name="operations/spam") # 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 - response = client.export_deployment_statefile(request) + response = client.unlock_deployment(request) # Establish that the response is the type that we expect. - assert isinstance(response, config.Statefile) - assert response.signed_uri == "signed_uri_value" + assert response.operation.name == "operations/spam" -def test_export_deployment_statefile_rest_required_fields( - request_type=config.ExportDeploymentStatefileRequest, +def test_unlock_deployment_rest_required_fields( + request_type=config.UnlockDeploymentRequest, ): transport_class = transports.ConfigRestTransport request_init = {} - request_init["parent"] = "" + request_init["name"] = "" + request_init["lock_id"] = 0 request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -8079,21 +10639,24 @@ def test_export_deployment_statefile_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).export_deployment_statefile._get_unset_required_fields(jsonified_request) + ).unlock_deployment._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["name"] = "name_value" + jsonified_request["lockId"] = 725 unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).export_deployment_statefile._get_unset_required_fields(jsonified_request) + ).unlock_deployment._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 "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(), @@ -8102,7 +10665,7 @@ def test_export_deployment_statefile_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = config.Statefile() + 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 @@ -8122,32 +10685,37 @@ def test_export_deployment_statefile_rest_required_fields( 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 - response = client.export_deployment_statefile(request) + 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_export_deployment_statefile_rest_unset_required_fields(): +def test_unlock_deployment_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",))) + unset_fields = transport.unlock_deployment._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "name", + "lockId", + ) + ) + ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_export_deployment_statefile_rest_interceptors(null_interceptor): +def test_unlock_deployment_rest_interceptors(null_interceptor): transport = transports.ConfigRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.ConfigRestInterceptor(), @@ -8158,15 +10726,15 @@ def test_export_deployment_statefile_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.ConfigRestInterceptor, "post_export_deployment_statefile" + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.ConfigRestInterceptor, "post_unlock_deployment" ) as post, mock.patch.object( - transports.ConfigRestInterceptor, "pre_export_deployment_statefile" + transports.ConfigRestInterceptor, "pre_unlock_deployment" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = config.ExportDeploymentStatefileRequest.pb( - config.ExportDeploymentStatefileRequest() - ) + pb_message = config.UnlockDeploymentRequest.pb(config.UnlockDeploymentRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -8177,17 +10745,19 @@ def test_export_deployment_statefile_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = config.Statefile.to_json(config.Statefile()) + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) - request = config.ExportDeploymentStatefileRequest() + request = config.UnlockDeploymentRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = config.Statefile() + post.return_value = operations_pb2.Operation() - client.export_deployment_statefile( + client.unlock_deployment( request, metadata=[ ("key", "val"), @@ -8199,8 +10769,8 @@ def test_export_deployment_statefile_rest_interceptors(null_interceptor): post.assert_called_once() -def test_export_deployment_statefile_rest_bad_request( - transport: str = "rest", request_type=config.ExportDeploymentStatefileRequest +def test_unlock_deployment_rest_bad_request( + transport: str = "rest", request_type=config.UnlockDeploymentRequest ): client = ConfigClient( credentials=ga_credentials.AnonymousCredentials(), @@ -8208,22 +10778,81 @@ def test_export_deployment_statefile_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/deployments/sample3"} + 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 = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.export_deployment_statefile(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() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.unlock_deployment(request) + + +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 + + 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_deployment_statefile_rest_error(): +def test_unlock_deployment_rest_error(): client = ConfigClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -8232,52 +10861,58 @@ def test_export_deployment_statefile_rest_error(): @pytest.mark.parametrize( "request_type", [ - config.ExportRevisionStatefileRequest, + config.ExportLockInfoRequest, dict, ], ) -def test_export_revision_statefile_rest(request_type): +def test_export_lock_info_rest(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_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.Statefile( - signed_uri="signed_uri_value", + 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 = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = config.Statefile.pb(return_value) + 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 - response = client.export_revision_statefile(request) + response = client.export_lock_info(request) # Establish that the response is the type that we expect. - assert isinstance(response, config.Statefile) - assert response.signed_uri == "signed_uri_value" + 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_revision_statefile_rest_required_fields( - request_type=config.ExportRevisionStatefileRequest, +def test_export_lock_info_rest_required_fields( + request_type=config.ExportLockInfoRequest, ): transport_class = transports.ConfigRestTransport request_init = {} - request_init["parent"] = "" + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -8292,21 +10927,21 @@ def test_export_revision_statefile_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).export_revision_statefile._get_unset_required_fields(jsonified_request) + ).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["parent"] = "parent_value" + jsonified_request["name"] = "name_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).export_revision_statefile._get_unset_required_fields(jsonified_request) + ).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 "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = ConfigClient( credentials=ga_credentials.AnonymousCredentials(), @@ -8315,7 +10950,7 @@ def test_export_revision_statefile_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = config.Statefile() + 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 @@ -8327,40 +10962,39 @@ def test_export_revision_statefile_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "get", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = config.Statefile.pb(return_value) + 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 - response = client.export_revision_statefile(request) + 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_revision_statefile_rest_unset_required_fields(): +def test_export_lock_info_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",))) + unset_fields = transport.export_lock_info._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_export_revision_statefile_rest_interceptors(null_interceptor): +def test_export_lock_info_rest_interceptors(null_interceptor): transport = transports.ConfigRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.ConfigRestInterceptor(), @@ -8371,15 +11005,13 @@ def test_export_revision_statefile_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.ConfigRestInterceptor, "post_export_revision_statefile" + transports.ConfigRestInterceptor, "post_export_lock_info" ) as post, mock.patch.object( - transports.ConfigRestInterceptor, "pre_export_revision_statefile" + transports.ConfigRestInterceptor, "pre_export_lock_info" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = config.ExportRevisionStatefileRequest.pb( - config.ExportRevisionStatefileRequest() - ) + pb_message = config.ExportLockInfoRequest.pb(config.ExportLockInfoRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -8390,17 +11022,17 @@ def test_export_revision_statefile_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = config.Statefile.to_json(config.Statefile()) + req.return_value._content = config.LockInfo.to_json(config.LockInfo()) - request = config.ExportRevisionStatefileRequest() + request = config.ExportLockInfoRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = config.Statefile() + post.return_value = config.LockInfo() - client.export_revision_statefile( + client.export_lock_info( request, metadata=[ ("key", "val"), @@ -8412,8 +11044,8 @@ def test_export_revision_statefile_rest_interceptors(null_interceptor): post.assert_called_once() -def test_export_revision_statefile_rest_bad_request( - transport: str = "rest", request_type=config.ExportRevisionStatefileRequest +def test_export_lock_info_rest_bad_request( + transport: str = "rest", request_type=config.ExportLockInfoRequest ): client = ConfigClient( credentials=ga_credentials.AnonymousCredentials(), @@ -8421,9 +11053,7 @@ def test_export_revision_statefile_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = { - "parent": "projects/sample1/locations/sample2/deployments/sample3/revisions/sample4" - } + 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. @@ -8435,10 +11065,69 @@ def test_export_revision_statefile_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.export_revision_statefile(request) + client.export_lock_info(request) -def test_export_revision_statefile_rest_error(): +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 + + 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_export_lock_info_rest_error(): client = ConfigClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -8447,51 +11136,156 @@ def test_export_revision_statefile_rest_error(): @pytest.mark.parametrize( "request_type", [ - config.ImportStatefileRequest, + config.CreatePreviewRequest, dict, ], ) -def test_import_statefile_rest(request_type): +def test_create_preview_rest(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"} + # 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", + } + # 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 = config.Statefile( - signed_uri="signed_uri_value", - ) + return_value = operations_pb2.Operation(name="operations/spam") # 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 - response = client.import_statefile(request) + response = client.create_preview(request) # Establish that the response is the type that we expect. - assert isinstance(response, config.Statefile) - assert response.signed_uri == "signed_uri_value" + assert response.operation.name == "operations/spam" -def test_import_statefile_rest_required_fields( - request_type=config.ImportStatefileRequest, -): +def test_create_preview_rest_required_fields(request_type=config.CreatePreviewRequest): 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( @@ -8506,24 +11300,28 @@ def test_import_statefile_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).import_statefile._get_unset_required_fields(jsonified_request) + ).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" - jsonified_request["lockId"] = 725 unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).import_statefile._get_unset_required_fields(jsonified_request) + ).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" - assert "lockId" in jsonified_request - assert jsonified_request["lockId"] == 725 client = ConfigClient( credentials=ga_credentials.AnonymousCredentials(), @@ -8532,7 +11330,7 @@ def test_import_statefile_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = config.Statefile() + 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 @@ -8552,40 +11350,42 @@ def test_import_statefile_rest_required_fields( 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 - response = client.import_statefile(request) + 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_import_statefile_rest_unset_required_fields(): +def test_create_preview_rest_unset_required_fields(): transport = transports.ConfigRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.import_statefile._get_unset_required_fields({}) + unset_fields = transport.create_preview._get_unset_required_fields({}) assert set(unset_fields) == ( - set(()) + set( + ( + "previewId", + "requestId", + ) + ) & set( ( "parent", - "lockId", + "preview", ) ) ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_import_statefile_rest_interceptors(null_interceptor): +def test_create_preview_rest_interceptors(null_interceptor): transport = transports.ConfigRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.ConfigRestInterceptor(), @@ -8596,13 +11396,15 @@ def test_import_statefile_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.ConfigRestInterceptor, "post_import_statefile" + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.ConfigRestInterceptor, "post_create_preview" ) as post, mock.patch.object( - transports.ConfigRestInterceptor, "pre_import_statefile" + transports.ConfigRestInterceptor, "pre_create_preview" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = config.ImportStatefileRequest.pb(config.ImportStatefileRequest()) + pb_message = config.CreatePreviewRequest.pb(config.CreatePreviewRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -8613,17 +11415,19 @@ def test_import_statefile_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = config.Statefile.to_json(config.Statefile()) + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) - request = config.ImportStatefileRequest() + request = config.CreatePreviewRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = config.Statefile() + post.return_value = operations_pb2.Operation() - client.import_statefile( + client.create_preview( request, metadata=[ ("key", "val"), @@ -8635,8 +11439,8 @@ def test_import_statefile_rest_interceptors(null_interceptor): post.assert_called_once() -def test_import_statefile_rest_bad_request( - transport: str = "rest", request_type=config.ImportStatefileRequest +def test_create_preview_rest_bad_request( + transport: str = "rest", request_type=config.CreatePreviewRequest ): client = ConfigClient( credentials=ga_credentials.AnonymousCredentials(), @@ -8644,7 +11448,7 @@ def test_import_statefile_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/deployments/sample3"} + 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. @@ -8656,10 +11460,10 @@ def test_import_statefile_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.import_statefile(request) + client.create_preview(request) -def test_import_statefile_rest_flattened(): +def test_create_preview_rest_flattened(): client = ConfigClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -8668,43 +11472,42 @@ def test_import_statefile_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = config.Statefile() + 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/deployments/sample3" - } + sample_request = {"parent": "projects/sample1/locations/sample2"} # get truthy value for each flattened field mock_args = dict( parent="parent_value", - lock_id=725, + 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 - # 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 - client.import_statefile(**mock_args) + 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/*/deployments/*}:importState" - % client.transport._host, + "%s/v1/{parent=projects/*/locations/*}/previews" % client.transport._host, args[1], ) -def test_import_statefile_rest_flattened_error(transport: str = "rest"): +def test_create_preview_rest_flattened_error(transport: str = "rest"): client = ConfigClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -8713,14 +11516,18 @@ def test_import_statefile_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.import_statefile( - config.ImportStatefileRequest(), + client.create_preview( + config.CreatePreviewRequest(), parent="parent_value", - lock_id=725, + preview=config.Preview( + terraform_blueprint=config.TerraformBlueprint( + gcs_source="gcs_source_value" + ) + ), ) -def test_import_statefile_rest_error(): +def test_create_preview_rest_error(): client = ConfigClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -8729,46 +11536,68 @@ def test_import_statefile_rest_error(): @pytest.mark.parametrize( "request_type", [ - config.DeleteStatefileRequest, + config.GetPreviewRequest, dict, ], ) -def test_delete_statefile_rest(request_type): +def test_get_preview_rest(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_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 = None + 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", + ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - json_return_value = "" + # Convert return value to protobuf type + return_value = 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 - response = client.delete_statefile(request) + response = client.get_preview(request) # Establish that the response is the type that we expect. - assert response is None + 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" -def test_delete_statefile_rest_required_fields( - request_type=config.DeleteStatefileRequest, -): +def test_get_preview_rest_required_fields(request_type=config.GetPreviewRequest): 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( @@ -8783,24 +11612,21 @@ def test_delete_statefile_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_statefile._get_unset_required_fields(jsonified_request) + ).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" - jsonified_request["lockId"] = 725 unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_statefile._get_unset_required_fields(jsonified_request) + ).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" - assert "lockId" in jsonified_request - assert jsonified_request["lockId"] == 725 client = ConfigClient( credentials=ga_credentials.AnonymousCredentials(), @@ -8809,7 +11635,7 @@ def test_delete_statefile_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = None + 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 @@ -8821,45 +11647,39 @@ def test_delete_statefile_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "get", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - json_return_value = "" + + # Convert return value to protobuf type + return_value = 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 - response = client.delete_statefile(request) + 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_delete_statefile_rest_unset_required_fields(): +def test_get_preview_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", - ) - ) - ) + unset_fields = transport.get_preview._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_statefile_rest_interceptors(null_interceptor): +def test_get_preview_rest_interceptors(null_interceptor): transport = transports.ConfigRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.ConfigRestInterceptor(), @@ -8870,10 +11690,13 @@ def test_delete_statefile_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.ConfigRestInterceptor, "pre_delete_statefile" + transports.ConfigRestInterceptor, "post_get_preview" + ) as post, mock.patch.object( + transports.ConfigRestInterceptor, "pre_get_preview" ) as pre: pre.assert_not_called() - pb_message = config.DeleteStatefileRequest.pb(config.DeleteStatefileRequest()) + post.assert_not_called() + pb_message = config.GetPreviewRequest.pb(config.GetPreviewRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -8884,15 +11707,17 @@ def test_delete_statefile_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() + req.return_value._content = config.Preview.to_json(config.Preview()) - request = config.DeleteStatefileRequest() + request = config.GetPreviewRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata + post.return_value = config.Preview() - client.delete_statefile( + client.get_preview( request, metadata=[ ("key", "val"), @@ -8901,10 +11726,11 @@ def test_delete_statefile_rest_interceptors(null_interceptor): ) pre.assert_called_once() + post.assert_called_once() -def test_delete_statefile_rest_bad_request( - transport: str = "rest", request_type=config.DeleteStatefileRequest +def test_get_preview_rest_bad_request( + transport: str = "rest", request_type=config.GetPreviewRequest ): client = ConfigClient( credentials=ga_credentials.AnonymousCredentials(), @@ -8912,7 +11738,7 @@ def test_delete_statefile_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/deployments/sample3"} + 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. @@ -8924,10 +11750,10 @@ def test_delete_statefile_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.delete_statefile(request) + client.get_preview(request) -def test_delete_statefile_rest_flattened(): +def test_get_preview_rest_flattened(): client = ConfigClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -8936,12 +11762,10 @@ def test_delete_statefile_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = None + return_value = config.Preview() # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/deployments/sample3" - } + sample_request = {"name": "projects/sample1/locations/sample2/previews/sample3"} # get truthy value for each flattened field mock_args = dict( @@ -8952,24 +11776,25 @@ def test_delete_statefile_rest_flattened(): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - json_return_value = "" + # Convert return value to protobuf type + return_value = 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 - client.delete_statefile(**mock_args) + 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/*/deployments/*}:deleteState" - % client.transport._host, + "%s/v1/{name=projects/*/locations/*/previews/*}" % client.transport._host, args[1], ) -def test_delete_statefile_rest_flattened_error(transport: str = "rest"): +def test_get_preview_rest_flattened_error(transport: str = "rest"): client = ConfigClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -8978,13 +11803,13 @@ def test_delete_statefile_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.delete_statefile( - config.DeleteStatefileRequest(), + client.get_preview( + config.GetPreviewRequest(), name="name_value", ) -def test_delete_statefile_rest_error(): +def test_get_preview_rest_error(): client = ConfigClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -8993,45 +11818,50 @@ def test_delete_statefile_rest_error(): @pytest.mark.parametrize( "request_type", [ - config.LockDeploymentRequest, + config.ListPreviewsRequest, dict, ], ) -def test_lock_deployment_rest(request_type): +def test_list_previews_rest(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_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 = operations_pb2.Operation(name="operations/spam") + return_value = config.ListPreviewsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) # 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 - response = client.lock_deployment(request) + response = client.list_previews(request) # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" + assert isinstance(response, pagers.ListPreviewsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] -def test_lock_deployment_rest_required_fields( - request_type=config.LockDeploymentRequest, -): +def test_list_previews_rest_required_fields(request_type=config.ListPreviewsRequest): transport_class = transports.ConfigRestTransport request_init = {} - request_init["name"] = "" + request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -9046,21 +11876,30 @@ def test_lock_deployment_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).lock_deployment._get_unset_required_fields(jsonified_request) + ).list_previews._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["parent"] = "parent_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).lock_deployment._get_unset_required_fields(jsonified_request) + ).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 "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" client = ConfigClient( credentials=ga_credentials.AnonymousCredentials(), @@ -9069,7 +11908,7 @@ def test_lock_deployment_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = 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 @@ -9081,37 +11920,49 @@ def test_lock_deployment_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "get", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 + + # 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 - response = client.lock_deployment(request) + 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_lock_deployment_rest_unset_required_fields(): +def test_list_previews_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",))) + unset_fields = transport.list_previews._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_lock_deployment_rest_interceptors(null_interceptor): +def test_list_previews_rest_interceptors(null_interceptor): transport = transports.ConfigRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.ConfigRestInterceptor(), @@ -9122,15 +11973,13 @@ def test_lock_deployment_rest_interceptors(null_interceptor): ) 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" + transports.ConfigRestInterceptor, "post_list_previews" ) as post, mock.patch.object( - transports.ConfigRestInterceptor, "pre_lock_deployment" + transports.ConfigRestInterceptor, "pre_list_previews" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = config.LockDeploymentRequest.pb(config.LockDeploymentRequest()) + pb_message = config.ListPreviewsRequest.pb(config.ListPreviewsRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -9141,19 +11990,19 @@ def test_lock_deployment_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson( - operations_pb2.Operation() + req.return_value._content = config.ListPreviewsResponse.to_json( + config.ListPreviewsResponse() ) - request = config.LockDeploymentRequest() + request = config.ListPreviewsRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() + post.return_value = config.ListPreviewsResponse() - client.lock_deployment( + client.list_previews( request, metadata=[ ("key", "val"), @@ -9165,8 +12014,8 @@ def test_lock_deployment_rest_interceptors(null_interceptor): post.assert_called_once() -def test_lock_deployment_rest_bad_request( - transport: str = "rest", request_type=config.LockDeploymentRequest +def test_list_previews_rest_bad_request( + transport: str = "rest", request_type=config.ListPreviewsRequest ): client = ConfigClient( credentials=ga_credentials.AnonymousCredentials(), @@ -9174,7 +12023,7 @@ def test_lock_deployment_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/deployments/sample3"} + 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. @@ -9186,10 +12035,10 @@ def test_lock_deployment_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.lock_deployment(request) + client.list_previews(request) -def test_lock_deployment_rest_flattened(): +def test_list_previews_rest_flattened(): client = ConfigClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -9198,40 +12047,39 @@ def test_lock_deployment_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = config.ListPreviewsResponse() # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/deployments/sample3" - } + sample_request = {"parent": "projects/sample1/locations/sample2"} # get truthy value for each flattened field mock_args = dict( - name="name_value", + parent="parent_value", ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 + # 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 - client.lock_deployment(**mock_args) + 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/{name=projects/*/locations/*/deployments/*}:lock" - % client.transport._host, + "%s/v1/{parent=projects/*/locations/*}/previews" % client.transport._host, args[1], ) -def test_lock_deployment_rest_flattened_error(transport: str = "rest"): +def test_list_previews_rest_flattened_error(transport: str = "rest"): client = ConfigClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -9240,33 +12088,88 @@ def test_lock_deployment_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.lock_deployment( - config.LockDeploymentRequest(), - name="name_value", + client.list_previews( + config.ListPreviewsRequest(), + parent="parent_value", ) -def test_lock_deployment_rest_error(): +def test_list_previews_rest_pager(transport: str = "rest"): client = ConfigClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + 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 + @pytest.mark.parametrize( "request_type", [ - config.UnlockDeploymentRequest, + config.DeletePreviewRequest, dict, ], ) -def test_unlock_deployment_rest(request_type): +def test_delete_preview_rest(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_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. @@ -9281,20 +12184,17 @@ def test_unlock_deployment_rest(request_type): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.unlock_deployment(request) + response = client.delete_preview(request) # Establish that the response is the type that we expect. assert response.operation.name == "operations/spam" -def test_unlock_deployment_rest_required_fields( - request_type=config.UnlockDeploymentRequest, -): +def test_delete_preview_rest_required_fields(request_type=config.DeletePreviewRequest): 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( @@ -9309,24 +12209,23 @@ def test_unlock_deployment_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).unlock_deployment._get_unset_required_fields(jsonified_request) + ).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" - jsonified_request["lockId"] = 725 unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).unlock_deployment._get_unset_required_fields(jsonified_request) + ).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" - assert "lockId" in jsonified_request - assert jsonified_request["lockId"] == 725 client = ConfigClient( credentials=ga_credentials.AnonymousCredentials(), @@ -9347,10 +12246,9 @@ def test_unlock_deployment_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "delete", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() @@ -9360,32 +12258,24 @@ def test_unlock_deployment_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.unlock_deployment(request) + 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_unlock_deployment_rest_unset_required_fields(): +def test_delete_preview_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", - ) - ) - ) + unset_fields = transport.delete_preview._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId",)) & set(("name",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_unlock_deployment_rest_interceptors(null_interceptor): +def test_delete_preview_rest_interceptors(null_interceptor): transport = transports.ConfigRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.ConfigRestInterceptor(), @@ -9398,13 +12288,13 @@ def test_unlock_deployment_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( operation.Operation, "_set_result_from_operation" ), mock.patch.object( - transports.ConfigRestInterceptor, "post_unlock_deployment" + transports.ConfigRestInterceptor, "post_delete_preview" ) as post, mock.patch.object( - transports.ConfigRestInterceptor, "pre_unlock_deployment" + transports.ConfigRestInterceptor, "pre_delete_preview" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = config.UnlockDeploymentRequest.pb(config.UnlockDeploymentRequest()) + pb_message = config.DeletePreviewRequest.pb(config.DeletePreviewRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -9419,7 +12309,7 @@ def test_unlock_deployment_rest_interceptors(null_interceptor): operations_pb2.Operation() ) - request = config.UnlockDeploymentRequest() + request = config.DeletePreviewRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -9427,7 +12317,7 @@ def test_unlock_deployment_rest_interceptors(null_interceptor): pre.return_value = request, metadata post.return_value = operations_pb2.Operation() - client.unlock_deployment( + client.delete_preview( request, metadata=[ ("key", "val"), @@ -9439,8 +12329,8 @@ def test_unlock_deployment_rest_interceptors(null_interceptor): post.assert_called_once() -def test_unlock_deployment_rest_bad_request( - transport: str = "rest", request_type=config.UnlockDeploymentRequest +def test_delete_preview_rest_bad_request( + transport: str = "rest", request_type=config.DeletePreviewRequest ): client = ConfigClient( credentials=ga_credentials.AnonymousCredentials(), @@ -9448,7 +12338,7 @@ def test_unlock_deployment_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/deployments/sample3"} + 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. @@ -9460,10 +12350,10 @@ def test_unlock_deployment_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.unlock_deployment(request) + client.delete_preview(request) -def test_unlock_deployment_rest_flattened(): +def test_delete_preview_rest_flattened(): client = ConfigClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -9475,14 +12365,11 @@ def test_unlock_deployment_rest_flattened(): 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" - } + sample_request = {"name": "projects/sample1/locations/sample2/previews/sample3"} # get truthy value for each flattened field mock_args = dict( name="name_value", - lock_id=725, ) mock_args.update(sample_request) @@ -9493,20 +12380,19 @@ def test_unlock_deployment_rest_flattened(): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.unlock_deployment(**mock_args) + 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/*/deployments/*}:unlock" - % client.transport._host, + "%s/v1/{name=projects/*/locations/*/previews/*}" % client.transport._host, args[1], ) -def test_unlock_deployment_rest_flattened_error(transport: str = "rest"): +def test_delete_preview_rest_flattened_error(transport: str = "rest"): client = ConfigClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -9515,14 +12401,13 @@ def test_unlock_deployment_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.unlock_deployment( - config.UnlockDeploymentRequest(), + client.delete_preview( + config.DeletePreviewRequest(), name="name_value", - lock_id=725, ) -def test_unlock_deployment_rest_error(): +def test_delete_preview_rest_error(): client = ConfigClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -9531,58 +12416,47 @@ def test_unlock_deployment_rest_error(): @pytest.mark.parametrize( "request_type", [ - config.ExportLockInfoRequest, + config.ExportPreviewResultRequest, dict, ], ) -def test_export_lock_info_rest(request_type): +def test_export_preview_result_rest(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_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.LockInfo( - lock_id=725, - operation="operation_value", - info="info_value", - who="who_value", - version="version_value", - ) + return_value = config.ExportPreviewResultResponse() # 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) + 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 - response = client.export_lock_info(request) + response = client.export_preview_result(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" + assert isinstance(response, config.ExportPreviewResultResponse) -def test_export_lock_info_rest_required_fields( - request_type=config.ExportLockInfoRequest, +def test_export_preview_result_rest_required_fields( + request_type=config.ExportPreviewResultRequest, ): transport_class = transports.ConfigRestTransport request_init = {} - request_init["name"] = "" + request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -9597,21 +12471,21 @@ def test_export_lock_info_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).export_lock_info._get_unset_required_fields(jsonified_request) + ).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["name"] = "name_value" + jsonified_request["parent"] = "parent_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).export_lock_info._get_unset_required_fields(jsonified_request) + ).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 "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" client = ConfigClient( credentials=ga_credentials.AnonymousCredentials(), @@ -9620,7 +12494,7 @@ def test_export_lock_info_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = config.LockInfo() + 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 @@ -9632,39 +12506,40 @@ def test_export_lock_info_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "post", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = config.LockInfo.pb(return_value) + 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 - response = client.export_lock_info(request) + 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_lock_info_rest_unset_required_fields(): +def test_export_preview_result_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",))) + unset_fields = transport.export_preview_result._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_export_lock_info_rest_interceptors(null_interceptor): +def test_export_preview_result_rest_interceptors(null_interceptor): transport = transports.ConfigRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.ConfigRestInterceptor(), @@ -9675,13 +12550,15 @@ def test_export_lock_info_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.ConfigRestInterceptor, "post_export_lock_info" + transports.ConfigRestInterceptor, "post_export_preview_result" ) as post, mock.patch.object( - transports.ConfigRestInterceptor, "pre_export_lock_info" + transports.ConfigRestInterceptor, "pre_export_preview_result" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = config.ExportLockInfoRequest.pb(config.ExportLockInfoRequest()) + pb_message = config.ExportPreviewResultRequest.pb( + config.ExportPreviewResultRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -9692,17 +12569,19 @@ def test_export_lock_info_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = config.LockInfo.to_json(config.LockInfo()) + req.return_value._content = config.ExportPreviewResultResponse.to_json( + config.ExportPreviewResultResponse() + ) - request = config.ExportLockInfoRequest() + request = config.ExportPreviewResultRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = config.LockInfo() + post.return_value = config.ExportPreviewResultResponse() - client.export_lock_info( + client.export_preview_result( request, metadata=[ ("key", "val"), @@ -9714,8 +12593,8 @@ def test_export_lock_info_rest_interceptors(null_interceptor): post.assert_called_once() -def test_export_lock_info_rest_bad_request( - transport: str = "rest", request_type=config.ExportLockInfoRequest +def test_export_preview_result_rest_bad_request( + transport: str = "rest", request_type=config.ExportPreviewResultRequest ): client = ConfigClient( credentials=ga_credentials.AnonymousCredentials(), @@ -9723,7 +12602,7 @@ def test_export_lock_info_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/deployments/sample3"} + 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. @@ -9735,69 +12614,10 @@ def test_export_lock_info_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.export_lock_info(request) - - -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 - - 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", - ) + client.export_preview_result(request) -def test_export_lock_info_rest_error(): +def test_export_preview_result_rest_error(): client = ConfigClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -9958,6 +12778,11 @@ def test_config_base_transport(): "lock_deployment", "unlock_deployment", "export_lock_info", + "create_preview", + "get_preview", + "list_previews", + "delete_preview", + "export_preview_result", "set_iam_policy", "get_iam_policy", "test_iam_permissions", @@ -10292,6 +13117,21 @@ def test_config_client_transport_session_collision(transport_name): 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 def test_config_grpc_transport_channel(): @@ -10474,12 +13314,38 @@ def test_parse_deployment_path(): assert expected == actual -def test_resource_path(): +def test_preview_path(): project = "cuttlefish" location = "mussel" - deployment = "winkle" - revision = "nautilus" - resource = "scallop" + 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, @@ -10495,11 +13361,11 @@ def test_resource_path(): def test_parse_resource_path(): expected = { - "project": "abalone", - "location": "squid", - "deployment": "clam", - "revision": "whelk", - "resource": "octopus", + "project": "nudibranch", + "location": "cuttlefish", + "deployment": "mussel", + "revision": "winkle", + "resource": "nautilus", } path = ConfigClient.resource_path(**expected) @@ -10509,10 +13375,10 @@ def test_parse_resource_path(): def test_revision_path(): - project = "oyster" - location = "nudibranch" - deployment = "cuttlefish" - revision = "mussel" + project = "scallop" + location = "abalone" + deployment = "squid" + revision = "clam" expected = "projects/{project}/locations/{location}/deployments/{deployment}/revisions/{revision}".format( project=project, location=location, @@ -10525,10 +13391,10 @@ def test_revision_path(): def test_parse_revision_path(): expected = { - "project": "winkle", - "location": "nautilus", - "deployment": "scallop", - "revision": "abalone", + "project": "whelk", + "location": "octopus", + "deployment": "oyster", + "revision": "nudibranch", } path = ConfigClient.revision_path(**expected) @@ -10538,8 +13404,8 @@ def test_parse_revision_path(): def test_service_account_path(): - project = "squid" - service_account = "clam" + project = "cuttlefish" + service_account = "mussel" expected = "projects/{project}/serviceAccounts/{service_account}".format( project=project, service_account=service_account, @@ -10550,8 +13416,8 @@ def test_service_account_path(): def test_parse_service_account_path(): expected = { - "project": "whelk", - "service_account": "octopus", + "project": "winkle", + "service_account": "nautilus", } path = ConfigClient.service_account_path(**expected) @@ -10561,9 +13427,9 @@ def test_parse_service_account_path(): def test_worker_pool_path(): - project = "oyster" - location = "nudibranch" - worker_pool = "cuttlefish" + project = "scallop" + location = "abalone" + worker_pool = "squid" expected = ( "projects/{project}/locations/{location}/workerPools/{worker_pool}".format( project=project, @@ -10577,9 +13443,9 @@ def test_worker_pool_path(): def test_parse_worker_pool_path(): expected = { - "project": "mussel", - "location": "winkle", - "worker_pool": "nautilus", + "project": "clam", + "location": "whelk", + "worker_pool": "octopus", } path = ConfigClient.worker_pool_path(**expected) @@ -10589,7 +13455,7 @@ def test_parse_worker_pool_path(): def test_common_billing_account_path(): - billing_account = "scallop" + billing_account = "oyster" expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -10599,7 +13465,7 @@ def test_common_billing_account_path(): def test_parse_common_billing_account_path(): expected = { - "billing_account": "abalone", + "billing_account": "nudibranch", } path = ConfigClient.common_billing_account_path(**expected) @@ -10609,7 +13475,7 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): - folder = "squid" + folder = "cuttlefish" expected = "folders/{folder}".format( folder=folder, ) @@ -10619,7 +13485,7 @@ def test_common_folder_path(): def test_parse_common_folder_path(): expected = { - "folder": "clam", + "folder": "mussel", } path = ConfigClient.common_folder_path(**expected) @@ -10629,7 +13495,7 @@ def test_parse_common_folder_path(): def test_common_organization_path(): - organization = "whelk" + organization = "winkle" expected = "organizations/{organization}".format( organization=organization, ) @@ -10639,7 +13505,7 @@ def test_common_organization_path(): def test_parse_common_organization_path(): expected = { - "organization": "octopus", + "organization": "nautilus", } path = ConfigClient.common_organization_path(**expected) @@ -10649,7 +13515,7 @@ def test_parse_common_organization_path(): def test_common_project_path(): - project = "oyster" + project = "scallop" expected = "projects/{project}".format( project=project, ) @@ -10659,7 +13525,7 @@ def test_common_project_path(): def test_parse_common_project_path(): expected = { - "project": "nudibranch", + "project": "abalone", } path = ConfigClient.common_project_path(**expected) @@ -10669,8 +13535,8 @@ def test_parse_common_project_path(): def test_common_location_path(): - project = "cuttlefish" - location = "mussel" + project = "squid" + location = "clam" expected = "projects/{project}/locations/{location}".format( project=project, location=location, @@ -10681,8 +13547,8 @@ def test_common_location_path(): def test_parse_common_location_path(): expected = { - "project": "winkle", - "location": "nautilus", + "project": "whelk", + "location": "octopus", } path = ConfigClient.common_location_path(**expected)