diff --git a/owl-bot-staging/google-cloud-service-management/v1/.coveragerc b/owl-bot-staging/google-cloud-service-management/v1/.coveragerc deleted file mode 100644 index e890e9afc685..000000000000 --- a/owl-bot-staging/google-cloud-service-management/v1/.coveragerc +++ /dev/null @@ -1,13 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/cloud/servicemanagement/__init__.py - google/cloud/servicemanagement/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-service-management/v1/.flake8 b/owl-bot-staging/google-cloud-service-management/v1/.flake8 deleted file mode 100644 index 29227d4cf419..000000000000 --- a/owl-bot-staging/google-cloud-service-management/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-service-management/v1/MANIFEST.in b/owl-bot-staging/google-cloud-service-management/v1/MANIFEST.in deleted file mode 100644 index 224a04acb727..000000000000 --- a/owl-bot-staging/google-cloud-service-management/v1/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/cloud/servicemanagement *.py -recursive-include google/cloud/servicemanagement_v1 *.py diff --git a/owl-bot-staging/google-cloud-service-management/v1/README.rst b/owl-bot-staging/google-cloud-service-management/v1/README.rst deleted file mode 100644 index 318a1e17e402..000000000000 --- a/owl-bot-staging/google-cloud-service-management/v1/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Cloud Servicemanagement 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 Servicemanagement 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-service-management/v1/docs/_static/custom.css b/owl-bot-staging/google-cloud-service-management/v1/docs/_static/custom.css deleted file mode 100644 index 06423be0b592..000000000000 --- a/owl-bot-staging/google-cloud-service-management/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-service-management/v1/docs/conf.py b/owl-bot-staging/google-cloud-service-management/v1/docs/conf.py deleted file mode 100644 index 7a520dba3a59..000000000000 --- a/owl-bot-staging/google-cloud-service-management/v1/docs/conf.py +++ /dev/null @@ -1,376 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-service-management 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-service-management" -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-service-management-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-service-management.tex", - u"google-cloud-service-management 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-service-management", - u"Google Cloud Servicemanagement 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-service-management", - u"google-cloud-service-management Documentation", - author, - "google-cloud-service-management", - "GAPIC library for Google Cloud Servicemanagement 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-service-management/v1/docs/index.rst b/owl-bot-staging/google-cloud-service-management/v1/docs/index.rst deleted file mode 100644 index bd12b79d8c5d..000000000000 --- a/owl-bot-staging/google-cloud-service-management/v1/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - servicemanagement_v1/services_ - servicemanagement_v1/types_ diff --git a/owl-bot-staging/google-cloud-service-management/v1/docs/servicemanagement_v1/service_manager.rst b/owl-bot-staging/google-cloud-service-management/v1/docs/servicemanagement_v1/service_manager.rst deleted file mode 100644 index 54acafe01d57..000000000000 --- a/owl-bot-staging/google-cloud-service-management/v1/docs/servicemanagement_v1/service_manager.rst +++ /dev/null @@ -1,10 +0,0 @@ -ServiceManager --------------------------------- - -.. automodule:: google.cloud.servicemanagement_v1.services.service_manager - :members: - :inherited-members: - -.. automodule:: google.cloud.servicemanagement_v1.services.service_manager.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/google-cloud-service-management/v1/docs/servicemanagement_v1/services_.rst b/owl-bot-staging/google-cloud-service-management/v1/docs/servicemanagement_v1/services_.rst deleted file mode 100644 index 1ced7cc091f6..000000000000 --- a/owl-bot-staging/google-cloud-service-management/v1/docs/servicemanagement_v1/services_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Services for Google Cloud Servicemanagement v1 API -================================================== -.. toctree:: - :maxdepth: 2 - - service_manager diff --git a/owl-bot-staging/google-cloud-service-management/v1/docs/servicemanagement_v1/types_.rst b/owl-bot-staging/google-cloud-service-management/v1/docs/servicemanagement_v1/types_.rst deleted file mode 100644 index f53a66140e4a..000000000000 --- a/owl-bot-staging/google-cloud-service-management/v1/docs/servicemanagement_v1/types_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Types for Google Cloud Servicemanagement v1 API -=============================================== - -.. automodule:: google.cloud.servicemanagement_v1.types - :members: - :show-inheritance: diff --git a/owl-bot-staging/google-cloud-service-management/v1/google/cloud/servicemanagement/__init__.py b/owl-bot-staging/google-cloud-service-management/v1/google/cloud/servicemanagement/__init__.py deleted file mode 100644 index f2ed5ae44dee..000000000000 --- a/owl-bot-staging/google-cloud-service-management/v1/google/cloud/servicemanagement/__init__.py +++ /dev/null @@ -1,83 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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.servicemanagement import gapic_version as package_version - -__version__ = package_version.__version__ - - -from google.cloud.servicemanagement_v1.services.service_manager.client import ServiceManagerClient -from google.cloud.servicemanagement_v1.services.service_manager.async_client import ServiceManagerAsyncClient - -from google.cloud.servicemanagement_v1.types.resources import ChangeReport -from google.cloud.servicemanagement_v1.types.resources import ConfigFile -from google.cloud.servicemanagement_v1.types.resources import ConfigRef -from google.cloud.servicemanagement_v1.types.resources import ConfigSource -from google.cloud.servicemanagement_v1.types.resources import Diagnostic -from google.cloud.servicemanagement_v1.types.resources import ManagedService -from google.cloud.servicemanagement_v1.types.resources import OperationMetadata -from google.cloud.servicemanagement_v1.types.resources import Rollout -from google.cloud.servicemanagement_v1.types.servicemanager import CreateServiceConfigRequest -from google.cloud.servicemanagement_v1.types.servicemanager import CreateServiceRequest -from google.cloud.servicemanagement_v1.types.servicemanager import CreateServiceRolloutRequest -from google.cloud.servicemanagement_v1.types.servicemanager import DeleteServiceRequest -from google.cloud.servicemanagement_v1.types.servicemanager import EnableServiceResponse -from google.cloud.servicemanagement_v1.types.servicemanager import GenerateConfigReportRequest -from google.cloud.servicemanagement_v1.types.servicemanager import GenerateConfigReportResponse -from google.cloud.servicemanagement_v1.types.servicemanager import GetServiceConfigRequest -from google.cloud.servicemanagement_v1.types.servicemanager import GetServiceRequest -from google.cloud.servicemanagement_v1.types.servicemanager import GetServiceRolloutRequest -from google.cloud.servicemanagement_v1.types.servicemanager import ListServiceConfigsRequest -from google.cloud.servicemanagement_v1.types.servicemanager import ListServiceConfigsResponse -from google.cloud.servicemanagement_v1.types.servicemanager import ListServiceRolloutsRequest -from google.cloud.servicemanagement_v1.types.servicemanager import ListServiceRolloutsResponse -from google.cloud.servicemanagement_v1.types.servicemanager import ListServicesRequest -from google.cloud.servicemanagement_v1.types.servicemanager import ListServicesResponse -from google.cloud.servicemanagement_v1.types.servicemanager import SubmitConfigSourceRequest -from google.cloud.servicemanagement_v1.types.servicemanager import SubmitConfigSourceResponse -from google.cloud.servicemanagement_v1.types.servicemanager import UndeleteServiceRequest -from google.cloud.servicemanagement_v1.types.servicemanager import UndeleteServiceResponse - -__all__ = ('ServiceManagerClient', - 'ServiceManagerAsyncClient', - 'ChangeReport', - 'ConfigFile', - 'ConfigRef', - 'ConfigSource', - 'Diagnostic', - 'ManagedService', - 'OperationMetadata', - 'Rollout', - 'CreateServiceConfigRequest', - 'CreateServiceRequest', - 'CreateServiceRolloutRequest', - 'DeleteServiceRequest', - 'EnableServiceResponse', - 'GenerateConfigReportRequest', - 'GenerateConfigReportResponse', - 'GetServiceConfigRequest', - 'GetServiceRequest', - 'GetServiceRolloutRequest', - 'ListServiceConfigsRequest', - 'ListServiceConfigsResponse', - 'ListServiceRolloutsRequest', - 'ListServiceRolloutsResponse', - 'ListServicesRequest', - 'ListServicesResponse', - 'SubmitConfigSourceRequest', - 'SubmitConfigSourceResponse', - 'UndeleteServiceRequest', - 'UndeleteServiceResponse', -) diff --git a/owl-bot-staging/google-cloud-service-management/v1/google/cloud/servicemanagement/gapic_version.py b/owl-bot-staging/google-cloud-service-management/v1/google/cloud/servicemanagement/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-cloud-service-management/v1/google/cloud/servicemanagement/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-service-management/v1/google/cloud/servicemanagement/py.typed b/owl-bot-staging/google-cloud-service-management/v1/google/cloud/servicemanagement/py.typed deleted file mode 100644 index 70f6a7b346b6..000000000000 --- a/owl-bot-staging/google-cloud-service-management/v1/google/cloud/servicemanagement/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-service-management package uses inline types. diff --git a/owl-bot-staging/google-cloud-service-management/v1/google/cloud/servicemanagement_v1/__init__.py b/owl-bot-staging/google-cloud-service-management/v1/google/cloud/servicemanagement_v1/__init__.py deleted file mode 100644 index a5870bfa608b..000000000000 --- a/owl-bot-staging/google-cloud-service-management/v1/google/cloud/servicemanagement_v1/__init__.py +++ /dev/null @@ -1,84 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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.servicemanagement_v1 import gapic_version as package_version - -__version__ = package_version.__version__ - - -from .services.service_manager import ServiceManagerClient -from .services.service_manager import ServiceManagerAsyncClient - -from .types.resources import ChangeReport -from .types.resources import ConfigFile -from .types.resources import ConfigRef -from .types.resources import ConfigSource -from .types.resources import Diagnostic -from .types.resources import ManagedService -from .types.resources import OperationMetadata -from .types.resources import Rollout -from .types.servicemanager import CreateServiceConfigRequest -from .types.servicemanager import CreateServiceRequest -from .types.servicemanager import CreateServiceRolloutRequest -from .types.servicemanager import DeleteServiceRequest -from .types.servicemanager import EnableServiceResponse -from .types.servicemanager import GenerateConfigReportRequest -from .types.servicemanager import GenerateConfigReportResponse -from .types.servicemanager import GetServiceConfigRequest -from .types.servicemanager import GetServiceRequest -from .types.servicemanager import GetServiceRolloutRequest -from .types.servicemanager import ListServiceConfigsRequest -from .types.servicemanager import ListServiceConfigsResponse -from .types.servicemanager import ListServiceRolloutsRequest -from .types.servicemanager import ListServiceRolloutsResponse -from .types.servicemanager import ListServicesRequest -from .types.servicemanager import ListServicesResponse -from .types.servicemanager import SubmitConfigSourceRequest -from .types.servicemanager import SubmitConfigSourceResponse -from .types.servicemanager import UndeleteServiceRequest -from .types.servicemanager import UndeleteServiceResponse - -__all__ = ( - 'ServiceManagerAsyncClient', -'ChangeReport', -'ConfigFile', -'ConfigRef', -'ConfigSource', -'CreateServiceConfigRequest', -'CreateServiceRequest', -'CreateServiceRolloutRequest', -'DeleteServiceRequest', -'Diagnostic', -'EnableServiceResponse', -'GenerateConfigReportRequest', -'GenerateConfigReportResponse', -'GetServiceConfigRequest', -'GetServiceRequest', -'GetServiceRolloutRequest', -'ListServiceConfigsRequest', -'ListServiceConfigsResponse', -'ListServiceRolloutsRequest', -'ListServiceRolloutsResponse', -'ListServicesRequest', -'ListServicesResponse', -'ManagedService', -'OperationMetadata', -'Rollout', -'ServiceManagerClient', -'SubmitConfigSourceRequest', -'SubmitConfigSourceResponse', -'UndeleteServiceRequest', -'UndeleteServiceResponse', -) diff --git a/owl-bot-staging/google-cloud-service-management/v1/google/cloud/servicemanagement_v1/gapic_metadata.json b/owl-bot-staging/google-cloud-service-management/v1/google/cloud/servicemanagement_v1/gapic_metadata.json deleted file mode 100644 index 8d71fcd6a7d6..000000000000 --- a/owl-bot-staging/google-cloud-service-management/v1/google/cloud/servicemanagement_v1/gapic_metadata.json +++ /dev/null @@ -1,223 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.cloud.servicemanagement_v1", - "protoPackage": "google.api.servicemanagement.v1", - "schema": "1.0", - "services": { - "ServiceManager": { - "clients": { - "grpc": { - "libraryClient": "ServiceManagerClient", - "rpcs": { - "CreateService": { - "methods": [ - "create_service" - ] - }, - "CreateServiceConfig": { - "methods": [ - "create_service_config" - ] - }, - "CreateServiceRollout": { - "methods": [ - "create_service_rollout" - ] - }, - "DeleteService": { - "methods": [ - "delete_service" - ] - }, - "GenerateConfigReport": { - "methods": [ - "generate_config_report" - ] - }, - "GetService": { - "methods": [ - "get_service" - ] - }, - "GetServiceConfig": { - "methods": [ - "get_service_config" - ] - }, - "GetServiceRollout": { - "methods": [ - "get_service_rollout" - ] - }, - "ListServiceConfigs": { - "methods": [ - "list_service_configs" - ] - }, - "ListServiceRollouts": { - "methods": [ - "list_service_rollouts" - ] - }, - "ListServices": { - "methods": [ - "list_services" - ] - }, - "SubmitConfigSource": { - "methods": [ - "submit_config_source" - ] - }, - "UndeleteService": { - "methods": [ - "undelete_service" - ] - } - } - }, - "grpc-async": { - "libraryClient": "ServiceManagerAsyncClient", - "rpcs": { - "CreateService": { - "methods": [ - "create_service" - ] - }, - "CreateServiceConfig": { - "methods": [ - "create_service_config" - ] - }, - "CreateServiceRollout": { - "methods": [ - "create_service_rollout" - ] - }, - "DeleteService": { - "methods": [ - "delete_service" - ] - }, - "GenerateConfigReport": { - "methods": [ - "generate_config_report" - ] - }, - "GetService": { - "methods": [ - "get_service" - ] - }, - "GetServiceConfig": { - "methods": [ - "get_service_config" - ] - }, - "GetServiceRollout": { - "methods": [ - "get_service_rollout" - ] - }, - "ListServiceConfigs": { - "methods": [ - "list_service_configs" - ] - }, - "ListServiceRollouts": { - "methods": [ - "list_service_rollouts" - ] - }, - "ListServices": { - "methods": [ - "list_services" - ] - }, - "SubmitConfigSource": { - "methods": [ - "submit_config_source" - ] - }, - "UndeleteService": { - "methods": [ - "undelete_service" - ] - } - } - }, - "rest": { - "libraryClient": "ServiceManagerClient", - "rpcs": { - "CreateService": { - "methods": [ - "create_service" - ] - }, - "CreateServiceConfig": { - "methods": [ - "create_service_config" - ] - }, - "CreateServiceRollout": { - "methods": [ - "create_service_rollout" - ] - }, - "DeleteService": { - "methods": [ - "delete_service" - ] - }, - "GenerateConfigReport": { - "methods": [ - "generate_config_report" - ] - }, - "GetService": { - "methods": [ - "get_service" - ] - }, - "GetServiceConfig": { - "methods": [ - "get_service_config" - ] - }, - "GetServiceRollout": { - "methods": [ - "get_service_rollout" - ] - }, - "ListServiceConfigs": { - "methods": [ - "list_service_configs" - ] - }, - "ListServiceRollouts": { - "methods": [ - "list_service_rollouts" - ] - }, - "ListServices": { - "methods": [ - "list_services" - ] - }, - "SubmitConfigSource": { - "methods": [ - "submit_config_source" - ] - }, - "UndeleteService": { - "methods": [ - "undelete_service" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/google-cloud-service-management/v1/google/cloud/servicemanagement_v1/gapic_version.py b/owl-bot-staging/google-cloud-service-management/v1/google/cloud/servicemanagement_v1/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-cloud-service-management/v1/google/cloud/servicemanagement_v1/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-service-management/v1/google/cloud/servicemanagement_v1/py.typed b/owl-bot-staging/google-cloud-service-management/v1/google/cloud/servicemanagement_v1/py.typed deleted file mode 100644 index 70f6a7b346b6..000000000000 --- a/owl-bot-staging/google-cloud-service-management/v1/google/cloud/servicemanagement_v1/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-service-management package uses inline types. diff --git a/owl-bot-staging/google-cloud-service-management/v1/google/cloud/servicemanagement_v1/services/__init__.py b/owl-bot-staging/google-cloud-service-management/v1/google/cloud/servicemanagement_v1/services/__init__.py deleted file mode 100644 index 8f6cf068242c..000000000000 --- a/owl-bot-staging/google-cloud-service-management/v1/google/cloud/servicemanagement_v1/services/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-service-management/v1/google/cloud/servicemanagement_v1/services/service_manager/__init__.py b/owl-bot-staging/google-cloud-service-management/v1/google/cloud/servicemanagement_v1/services/service_manager/__init__.py deleted file mode 100644 index 9cfa5ac8fc74..000000000000 --- a/owl-bot-staging/google-cloud-service-management/v1/google/cloud/servicemanagement_v1/services/service_manager/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 ServiceManagerClient -from .async_client import ServiceManagerAsyncClient - -__all__ = ( - 'ServiceManagerClient', - 'ServiceManagerAsyncClient', -) diff --git a/owl-bot-staging/google-cloud-service-management/v1/google/cloud/servicemanagement_v1/services/service_manager/async_client.py b/owl-bot-staging/google-cloud-service-management/v1/google/cloud/servicemanagement_v1/services/service_manager/async_client.py deleted file mode 100644 index c643623015ab..000000000000 --- a/owl-bot-staging/google-cloud-service-management/v1/google/cloud/servicemanagement_v1/services/service_manager/async_client.py +++ /dev/null @@ -1,2388 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import logging as std_logging -from collections import OrderedDict -import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.servicemanagement_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, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore - -from google.api import auth_pb2 # type: ignore -from google.api import backend_pb2 # type: ignore -from google.api import billing_pb2 # type: ignore -from google.api import client_pb2 # type: ignore -from google.api import context_pb2 # type: ignore -from google.api import control_pb2 # type: ignore -from google.api import documentation_pb2 # type: ignore -from google.api import endpoint_pb2 # type: ignore -from google.api import http_pb2 # type: ignore -from google.api import log_pb2 # type: ignore -from google.api import logging_pb2 # type: ignore -from google.api import metric_pb2 # type: ignore -from google.api import monitored_resource_pb2 # type: ignore -from google.api import monitoring_pb2 # type: ignore -from google.api import quota_pb2 # type: ignore -from google.api import service_pb2 # type: ignore -from google.api import source_info_pb2 # type: ignore -from google.api import system_parameter_pb2 # type: ignore -from google.api import usage_pb2 # type: ignore -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.servicemanagement_v1.services.service_manager import pagers -from google.cloud.servicemanagement_v1.types import resources -from google.cloud.servicemanagement_v1.types import servicemanager -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 any_pb2 # type: ignore -from google.protobuf import api_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import type_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore -from .transports.base import ServiceManagerTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import ServiceManagerGrpcAsyncIOTransport -from .client import ServiceManagerClient - -try: - from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER -except ImportError: # pragma: NO COVER - CLIENT_LOGGING_SUPPORTED = False - -_LOGGER = std_logging.getLogger(__name__) - -class ServiceManagerAsyncClient: - """`Google Service Management - API `__ - """ - - _client: ServiceManagerClient - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = ServiceManagerClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = ServiceManagerClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = ServiceManagerClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = ServiceManagerClient._DEFAULT_UNIVERSE - - common_billing_account_path = staticmethod(ServiceManagerClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(ServiceManagerClient.parse_common_billing_account_path) - common_folder_path = staticmethod(ServiceManagerClient.common_folder_path) - parse_common_folder_path = staticmethod(ServiceManagerClient.parse_common_folder_path) - common_organization_path = staticmethod(ServiceManagerClient.common_organization_path) - parse_common_organization_path = staticmethod(ServiceManagerClient.parse_common_organization_path) - common_project_path = staticmethod(ServiceManagerClient.common_project_path) - parse_common_project_path = staticmethod(ServiceManagerClient.parse_common_project_path) - common_location_path = staticmethod(ServiceManagerClient.common_location_path) - parse_common_location_path = staticmethod(ServiceManagerClient.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: - ServiceManagerAsyncClient: The constructed client. - """ - return ServiceManagerClient.from_service_account_info.__func__(ServiceManagerAsyncClient, 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: - ServiceManagerAsyncClient: The constructed client. - """ - return ServiceManagerClient.from_service_account_file.__func__(ServiceManagerAsyncClient, 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 ServiceManagerClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> ServiceManagerTransport: - """Returns the transport used by the client instance. - - Returns: - ServiceManagerTransport: The transport used by the client instance. - """ - return self._client.transport - - @property - def api_endpoint(self): - """Return the API endpoint used by the client instance. - - Returns: - str: The API endpoint used by the client instance. - """ - return self._client._api_endpoint - - @property - def universe_domain(self) -> str: - """Return the universe domain used by the client instance. - - Returns: - str: The universe domain used - by the client instance. - """ - return self._client._universe_domain - - get_transport_class = ServiceManagerClient.get_transport_class - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, ServiceManagerTransport, Callable[..., ServiceManagerTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the service manager async client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Optional[Union[str,ServiceManagerTransport,Callable[..., ServiceManagerTransport]]]): - The transport to use, or a Callable that constructs and returns a new transport to use. - If a Callable is given, it will be called with the same set of initialization - arguments as used in the ServiceManagerTransport constructor. - If set to None, a transport is chosen automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto-switch to the - default mTLS endpoint if client certificate is present; this is - the default value). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - 3. The ``universe_domain`` property can be used to override the - default "googleapis.com" universe. Note that ``api_endpoint`` - property still takes precedence; and ``universe_domain`` is - currently not supported for mTLS. - - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = ServiceManagerClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER - _LOGGER.debug( - "Created client `google.api.servicemanagement_v1.ServiceManagerAsyncClient`.", - extra = { - "serviceName": "google.api.servicemanagement.v1.ServiceManager", - "universeDomain": getattr(self._client._transport._credentials, "universe_domain", ""), - "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", - "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), - } if hasattr(self._client._transport, "_credentials") else { - "serviceName": "google.api.servicemanagement.v1.ServiceManager", - "credentialsType": None, - } - ) - - async def list_services(self, - request: Optional[Union[servicemanager.ListServicesRequest, dict]] = None, - *, - producer_project_id: Optional[str] = None, - consumer_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListServicesAsyncPager: - r"""Lists managed services. - - Returns all public services. For authenticated users, - also returns all services the calling user has - "servicemanagement.services.get" permission for. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import servicemanagement_v1 - - async def sample_list_services(): - # Create a client - client = servicemanagement_v1.ServiceManagerAsyncClient() - - # Initialize request argument(s) - request = servicemanagement_v1.ListServicesRequest( - ) - - # Make the request - page_result = client.list_services(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.servicemanagement_v1.types.ListServicesRequest, dict]]): - The request object. Request message for ``ListServices`` method. - producer_project_id (:class:`str`): - Include services produced by the - specified project. - - This corresponds to the ``producer_project_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - consumer_id (:class:`str`): - Include services consumed by the specified consumer. - - The Google Service Management implementation accepts the - following forms: - - - project: - - This corresponds to the ``consumer_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.cloud.servicemanagement_v1.services.service_manager.pagers.ListServicesAsyncPager: - Response message for ListServices method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([producer_project_id, consumer_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.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, servicemanager.ListServicesRequest): - request = servicemanager.ListServicesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if producer_project_id is not None: - request.producer_project_id = producer_project_id - if consumer_id is not None: - request.consumer_id = consumer_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.list_services] - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListServicesAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_service(self, - request: Optional[Union[servicemanager.GetServiceRequest, dict]] = None, - *, - service_name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> resources.ManagedService: - r"""Gets a managed service. Authentication is required - unless the service is public. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import servicemanagement_v1 - - async def sample_get_service(): - # Create a client - client = servicemanagement_v1.ServiceManagerAsyncClient() - - # Initialize request argument(s) - request = servicemanagement_v1.GetServiceRequest( - service_name="service_name_value", - ) - - # Make the request - response = await client.get_service(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.servicemanagement_v1.types.GetServiceRequest, dict]]): - The request object. Request message for ``GetService`` method. - service_name (:class:`str`): - Required. The name of the service. See the - ``ServiceManager`` overview for naming requirements. For - example: ``example.googleapis.com``. - - This corresponds to the ``service_name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.cloud.servicemanagement_v1.types.ManagedService: - The full representation of a Service - that is managed by Google Service - Management. - - """ - # Create or coerce a 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([service_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.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, servicemanager.GetServiceRequest): - request = servicemanager.GetServiceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if service_name is not None: - request.service_name = service_name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.get_service] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("service_name", request.service_name), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_service(self, - request: Optional[Union[servicemanager.CreateServiceRequest, dict]] = None, - *, - service: Optional[resources.ManagedService] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: - r"""Creates a new managed service. - - A managed service is immutable, and is subject to - mandatory 30-day data retention. You cannot move a - service or recreate it within 30 days after deletion. - - One producer project can own no more than 500 services. - For security and reliability purposes, a production - service should be hosted in a dedicated producer - project. - - Operation - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import servicemanagement_v1 - - async def sample_create_service(): - # Create a client - client = servicemanagement_v1.ServiceManagerAsyncClient() - - # Initialize request argument(s) - request = servicemanagement_v1.CreateServiceRequest( - ) - - # Make the request - operation = client.create_service(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.servicemanagement_v1.types.CreateServiceRequest, dict]]): - The request object. Request message for CreateService - method. - service (:class:`google.cloud.servicemanagement_v1.types.ManagedService`): - Required. Initial values for the - service resource. - - This corresponds to the ``service`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.servicemanagement_v1.types.ManagedService` The full representation of a Service that is managed by - Google Service Management. - - """ - # Create or coerce a 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([service]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, servicemanager.CreateServiceRequest): - request = servicemanager.CreateServiceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if service is not None: - request.service = service - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_service] - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - resources.ManagedService, - metadata_type=resources.OperationMetadata, - ) - - # Done; return the response. - return response - - async def delete_service(self, - request: Optional[Union[servicemanager.DeleteServiceRequest, dict]] = None, - *, - service_name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: - r"""Deletes a managed service. This method will change the service - to the ``Soft-Delete`` state for 30 days. Within this period, - service producers may call - [UndeleteService][google.api.servicemanagement.v1.ServiceManager.UndeleteService] - to restore the service. After 30 days, the service will be - permanently deleted. - - Operation - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import servicemanagement_v1 - - async def sample_delete_service(): - # Create a client - client = servicemanagement_v1.ServiceManagerAsyncClient() - - # Initialize request argument(s) - request = servicemanagement_v1.DeleteServiceRequest( - service_name="service_name_value", - ) - - # Make the request - operation = client.delete_service(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.servicemanagement_v1.types.DeleteServiceRequest, dict]]): - The request object. Request message for DeleteService - method. - service_name (:class:`str`): - Required. The name of the service. See the - `overview `__ - for naming requirements. For example: - ``example.googleapis.com``. - - This corresponds to the ``service_name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([service_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.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, servicemanager.DeleteServiceRequest): - request = servicemanager.DeleteServiceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if service_name is not None: - request.service_name = service_name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.delete_service] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("service_name", request.service_name), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - empty_pb2.Empty, - metadata_type=resources.OperationMetadata, - ) - - # Done; return the response. - return response - - async def undelete_service(self, - request: Optional[Union[servicemanager.UndeleteServiceRequest, dict]] = None, - *, - service_name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: - r"""Revives a previously deleted managed service. The - method restores the service using the configuration at - the time the service was deleted. The target service - must exist and must have been deleted within the last 30 - days. - - Operation - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import servicemanagement_v1 - - async def sample_undelete_service(): - # Create a client - client = servicemanagement_v1.ServiceManagerAsyncClient() - - # Initialize request argument(s) - request = servicemanagement_v1.UndeleteServiceRequest( - service_name="service_name_value", - ) - - # Make the request - operation = client.undelete_service(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.servicemanagement_v1.types.UndeleteServiceRequest, dict]]): - The request object. Request message for UndeleteService - method. - service_name (:class:`str`): - Required. The name of the service. See the - `overview `__ - for naming requirements. For example: - ``example.googleapis.com``. - - This corresponds to the ``service_name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.servicemanagement_v1.types.UndeleteServiceResponse` - Response message for UndeleteService method. - - """ - # Create or coerce a 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([service_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.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, servicemanager.UndeleteServiceRequest): - request = servicemanager.UndeleteServiceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if service_name is not None: - request.service_name = service_name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.undelete_service] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("service_name", request.service_name), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - servicemanager.UndeleteServiceResponse, - metadata_type=resources.OperationMetadata, - ) - - # Done; return the response. - return response - - async def list_service_configs(self, - request: Optional[Union[servicemanager.ListServiceConfigsRequest, dict]] = None, - *, - service_name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListServiceConfigsAsyncPager: - r"""Lists the history of the service configuration for a - managed service, from the newest to the oldest. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import servicemanagement_v1 - - async def sample_list_service_configs(): - # Create a client - client = servicemanagement_v1.ServiceManagerAsyncClient() - - # Initialize request argument(s) - request = servicemanagement_v1.ListServiceConfigsRequest( - service_name="service_name_value", - ) - - # Make the request - page_result = client.list_service_configs(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.servicemanagement_v1.types.ListServiceConfigsRequest, dict]]): - The request object. Request message for - ListServiceConfigs method. - service_name (:class:`str`): - Required. The name of the service. See the - `overview `__ - for naming requirements. For example: - ``example.googleapis.com``. - - This corresponds to the ``service_name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.cloud.servicemanagement_v1.services.service_manager.pagers.ListServiceConfigsAsyncPager: - Response message for - ListServiceConfigs method. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([service_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.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, servicemanager.ListServiceConfigsRequest): - request = servicemanager.ListServiceConfigsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if service_name is not None: - request.service_name = service_name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.list_service_configs] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("service_name", request.service_name), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListServiceConfigsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_service_config(self, - request: Optional[Union[servicemanager.GetServiceConfigRequest, dict]] = None, - *, - service_name: Optional[str] = None, - config_id: Optional[str] = None, - view: Optional[servicemanager.GetServiceConfigRequest.ConfigView] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> service_pb2.Service: - r"""Gets a service configuration (version) for a managed - service. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import servicemanagement_v1 - - async def sample_get_service_config(): - # Create a client - client = servicemanagement_v1.ServiceManagerAsyncClient() - - # Initialize request argument(s) - request = servicemanagement_v1.GetServiceConfigRequest( - service_name="service_name_value", - config_id="config_id_value", - ) - - # Make the request - response = await client.get_service_config(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.servicemanagement_v1.types.GetServiceConfigRequest, dict]]): - The request object. Request message for GetServiceConfig - method. - service_name (:class:`str`): - Required. The name of the service. See the - `overview `__ - for naming requirements. For example: - ``example.googleapis.com``. - - This corresponds to the ``service_name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - config_id (:class:`str`): - Required. The id of the service configuration resource. - - This field must be specified for the server to return - all fields, including ``SourceInfo``. - - This corresponds to the ``config_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - view (:class:`google.cloud.servicemanagement_v1.types.GetServiceConfigRequest.ConfigView`): - Specifies which parts of the Service - Config should be returned in the - response. - - This corresponds to the ``view`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.api.service_pb2.Service: - Service is the root object of Google API service configuration (service - config). It describes the basic information about a - logical service, such as the service name and the - user-facing title, and delegates other aspects to - sub-sections. Each sub-section is either a proto - message or a repeated proto message that configures a - specific aspect, such as auth. For more information, - see each proto message definition. - - Example: - - type: google.api.Service name: - calendar.googleapis.com title: Google Calendar API - apis: - name: google.calendar.v3.Calendar - - visibility: - rules: - selector: "google.calendar.v3.*" - restriction: PREVIEW - - backend: - rules: - selector: "google.calendar.v3.*" - address: calendar.example.com - - authentication: - providers: - id: google_calendar_auth jwks_uri: - https://www.googleapis.com/oauth2/v1/certs - issuer: https://securetoken.google.com rules: - - selector: "*" requirements: provider_id: - google_calendar_auth - - """ - # Create or coerce a 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([service_name, config_id, view]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, servicemanager.GetServiceConfigRequest): - request = servicemanager.GetServiceConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if service_name is not None: - request.service_name = service_name - if config_id is not None: - request.config_id = config_id - if view is not None: - request.view = view - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.get_service_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("service_name", request.service_name), - ("config_id", request.config_id), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_service_config(self, - request: Optional[Union[servicemanager.CreateServiceConfigRequest, dict]] = None, - *, - service_name: Optional[str] = None, - service_config: Optional[service_pb2.Service] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> service_pb2.Service: - r"""Creates a new service configuration (version) for a managed - service. This method only stores the service configuration. To - roll out the service configuration to backend systems please - call - [CreateServiceRollout][google.api.servicemanagement.v1.ServiceManager.CreateServiceRollout]. - - Only the 100 most recent service configurations and ones - referenced by existing rollouts are kept for each service. The - rest will be deleted eventually. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import servicemanagement_v1 - - async def sample_create_service_config(): - # Create a client - client = servicemanagement_v1.ServiceManagerAsyncClient() - - # Initialize request argument(s) - request = servicemanagement_v1.CreateServiceConfigRequest( - service_name="service_name_value", - ) - - # Make the request - response = await client.create_service_config(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.servicemanagement_v1.types.CreateServiceConfigRequest, dict]]): - The request object. Request message for - CreateServiceConfig method. - service_name (:class:`str`): - Required. The name of the service. See the - `overview `__ - for naming requirements. For example: - ``example.googleapis.com``. - - This corresponds to the ``service_name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - service_config (:class:`google.api.service_pb2.Service`): - Required. The service configuration - resource. - - This corresponds to the ``service_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.api.service_pb2.Service: - Service is the root object of Google API service configuration (service - config). It describes the basic information about a - logical service, such as the service name and the - user-facing title, and delegates other aspects to - sub-sections. Each sub-section is either a proto - message or a repeated proto message that configures a - specific aspect, such as auth. For more information, - see each proto message definition. - - Example: - - type: google.api.Service name: - calendar.googleapis.com title: Google Calendar API - apis: - name: google.calendar.v3.Calendar - - visibility: - rules: - selector: "google.calendar.v3.*" - restriction: PREVIEW - - backend: - rules: - selector: "google.calendar.v3.*" - address: calendar.example.com - - authentication: - providers: - id: google_calendar_auth jwks_uri: - https://www.googleapis.com/oauth2/v1/certs - issuer: https://securetoken.google.com rules: - - selector: "*" requirements: provider_id: - google_calendar_auth - - """ - # Create or coerce a 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([service_name, service_config]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, servicemanager.CreateServiceConfigRequest): - request = servicemanager.CreateServiceConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if service_name is not None: - request.service_name = service_name - if service_config is not None: - request.service_config = service_config - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_service_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("service_name", request.service_name), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def submit_config_source(self, - request: Optional[Union[servicemanager.SubmitConfigSourceRequest, dict]] = None, - *, - service_name: Optional[str] = None, - config_source: Optional[resources.ConfigSource] = None, - validate_only: Optional[bool] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: - r"""Creates a new service configuration (version) for a managed - service based on user-supplied configuration source files (for - example: OpenAPI Specification). This method stores the source - configurations as well as the generated service configuration. - To rollout the service configuration to other services, please - call - [CreateServiceRollout][google.api.servicemanagement.v1.ServiceManager.CreateServiceRollout]. - - Only the 100 most recent configuration sources and ones - referenced by existing service configurtions are kept for each - service. The rest will be deleted eventually. - - Operation - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import servicemanagement_v1 - - async def sample_submit_config_source(): - # Create a client - client = servicemanagement_v1.ServiceManagerAsyncClient() - - # Initialize request argument(s) - request = servicemanagement_v1.SubmitConfigSourceRequest( - service_name="service_name_value", - ) - - # Make the request - operation = client.submit_config_source(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.servicemanagement_v1.types.SubmitConfigSourceRequest, dict]]): - The request object. Request message for - SubmitConfigSource method. - service_name (:class:`str`): - Required. The name of the service. See the - `overview `__ - for naming requirements. For example: - ``example.googleapis.com``. - - This corresponds to the ``service_name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - config_source (:class:`google.cloud.servicemanagement_v1.types.ConfigSource`): - Required. The source configuration - for the service. - - This corresponds to the ``config_source`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - validate_only (:class:`bool`): - Optional. If set, this will result in the generation of - a ``google.api.Service`` configuration based on the - ``ConfigSource`` provided, but the generated config and - the sources will NOT be persisted. - - This corresponds to the ``validate_only`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.servicemanagement_v1.types.SubmitConfigSourceResponse` - Response message for SubmitConfigSource method. - - """ - # Create or coerce a 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([service_name, config_source, validate_only]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, servicemanager.SubmitConfigSourceRequest): - request = servicemanager.SubmitConfigSourceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if service_name is not None: - request.service_name = service_name - if config_source is not None: - request.config_source = config_source - if validate_only is not None: - request.validate_only = validate_only - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.submit_config_source] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("service_name", request.service_name), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - servicemanager.SubmitConfigSourceResponse, - metadata_type=resources.OperationMetadata, - ) - - # Done; return the response. - return response - - async def list_service_rollouts(self, - request: Optional[Union[servicemanager.ListServiceRolloutsRequest, dict]] = None, - *, - service_name: Optional[str] = None, - filter: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListServiceRolloutsAsyncPager: - r"""Lists the history of the service configuration - rollouts for a managed service, from the newest to the - oldest. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import servicemanagement_v1 - - async def sample_list_service_rollouts(): - # Create a client - client = servicemanagement_v1.ServiceManagerAsyncClient() - - # Initialize request argument(s) - request = servicemanagement_v1.ListServiceRolloutsRequest( - service_name="service_name_value", - filter="filter_value", - ) - - # Make the request - page_result = client.list_service_rollouts(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.servicemanagement_v1.types.ListServiceRolloutsRequest, dict]]): - The request object. Request message for - 'ListServiceRollouts' - service_name (:class:`str`): - Required. The name of the service. See the - `overview `__ - for naming requirements. For example: - ``example.googleapis.com``. - - This corresponds to the ``service_name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - filter (:class:`str`): - Required. Use ``filter`` to return subset of rollouts. - The following filters are supported: - - -- By [status] - [google.api.servicemanagement.v1.Rollout.RolloutStatus]. - For example, ``filter='status=SUCCESS'`` - - -- By [strategy] - [google.api.servicemanagement.v1.Rollout.strategy]. For - example, ``filter='strategy=TrafficPercentStrategy'`` - - This corresponds to the ``filter`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.cloud.servicemanagement_v1.services.service_manager.pagers.ListServiceRolloutsAsyncPager: - Response message for - ListServiceRollouts method. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([service_name, filter]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, servicemanager.ListServiceRolloutsRequest): - request = servicemanager.ListServiceRolloutsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if service_name is not None: - request.service_name = service_name - if filter is not None: - request.filter = filter - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.list_service_rollouts] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("service_name", request.service_name), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListServiceRolloutsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_service_rollout(self, - request: Optional[Union[servicemanager.GetServiceRolloutRequest, dict]] = None, - *, - service_name: Optional[str] = None, - rollout_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> resources.Rollout: - r"""Gets a service configuration - [rollout][google.api.servicemanagement.v1.Rollout]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import servicemanagement_v1 - - async def sample_get_service_rollout(): - # Create a client - client = servicemanagement_v1.ServiceManagerAsyncClient() - - # Initialize request argument(s) - request = servicemanagement_v1.GetServiceRolloutRequest( - service_name="service_name_value", - rollout_id="rollout_id_value", - ) - - # Make the request - response = await client.get_service_rollout(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.servicemanagement_v1.types.GetServiceRolloutRequest, dict]]): - The request object. Request message for GetServiceRollout - method. - service_name (:class:`str`): - Required. The name of the service. See the - `overview `__ - for naming requirements. For example: - ``example.googleapis.com``. - - This corresponds to the ``service_name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - rollout_id (:class:`str`): - Required. The id of the rollout - resource. - - This corresponds to the ``rollout_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.cloud.servicemanagement_v1.types.Rollout: - A rollout resource that defines how - service configuration versions are - pushed to control plane systems. - Typically, you create a new version of - the service config, and then create a - Rollout to push the service config. - - """ - # Create or coerce a 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([service_name, rollout_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.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, servicemanager.GetServiceRolloutRequest): - request = servicemanager.GetServiceRolloutRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if service_name is not None: - request.service_name = service_name - if rollout_id is not None: - request.rollout_id = rollout_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.get_service_rollout] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("service_name", request.service_name), - ("rollout_id", request.rollout_id), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_service_rollout(self, - request: Optional[Union[servicemanager.CreateServiceRolloutRequest, dict]] = None, - *, - service_name: Optional[str] = None, - rollout: Optional[resources.Rollout] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation_async.AsyncOperation: - r"""Creates a new service configuration rollout. Based on - rollout, the Google Service Management will roll out the - service configurations to different backend services. - For example, the logging configuration will be pushed to - Google Cloud Logging. - - Please note that any previous pending and running - Rollouts and associated Operations will be automatically - cancelled so that the latest Rollout will not be blocked - by previous Rollouts. - - Only the 100 most recent (in any state) and the last 10 - successful (if not already part of the set of 100 most - recent) rollouts are kept for each service. The rest - will be deleted eventually. - - Operation - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import servicemanagement_v1 - - async def sample_create_service_rollout(): - # Create a client - client = servicemanagement_v1.ServiceManagerAsyncClient() - - # Initialize request argument(s) - request = servicemanagement_v1.CreateServiceRolloutRequest( - service_name="service_name_value", - ) - - # Make the request - operation = client.create_service_rollout(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.servicemanagement_v1.types.CreateServiceRolloutRequest, dict]]): - The request object. Request message for - 'CreateServiceRollout' - service_name (:class:`str`): - Required. The name of the service. See the - `overview `__ - for naming requirements. For example: - ``example.googleapis.com``. - - This corresponds to the ``service_name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - rollout (:class:`google.cloud.servicemanagement_v1.types.Rollout`): - Required. The rollout resource. The ``service_name`` - field is output only. - - This corresponds to the ``rollout`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.servicemanagement_v1.types.Rollout` A rollout resource that defines how service configuration versions are pushed - to control plane systems. Typically, you create a new - version of the service config, and then create a - Rollout to push the service config. - - """ - # Create or coerce a 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([service_name, rollout]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, servicemanager.CreateServiceRolloutRequest): - request = servicemanager.CreateServiceRolloutRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if service_name is not None: - request.service_name = service_name - if rollout is not None: - request.rollout = rollout - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_service_rollout] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("service_name", request.service_name), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - resources.Rollout, - metadata_type=resources.OperationMetadata, - ) - - # Done; return the response. - return response - - async def generate_config_report(self, - request: Optional[Union[servicemanager.GenerateConfigReportRequest, dict]] = None, - *, - new_config: Optional[any_pb2.Any] = None, - old_config: Optional[any_pb2.Any] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> servicemanager.GenerateConfigReportResponse: - r"""Generates and returns a report (errors, warnings and changes - from existing configurations) associated with - GenerateConfigReportRequest.new_value - - If GenerateConfigReportRequest.old_value is specified, - GenerateConfigReportRequest will contain a single ChangeReport - based on the comparison between - GenerateConfigReportRequest.new_value and - GenerateConfigReportRequest.old_value. If - GenerateConfigReportRequest.old_value is not specified, this - method will compare GenerateConfigReportRequest.new_value with - the last pushed service configuration. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import servicemanagement_v1 - - async def sample_generate_config_report(): - # Create a client - client = servicemanagement_v1.ServiceManagerAsyncClient() - - # Initialize request argument(s) - request = servicemanagement_v1.GenerateConfigReportRequest( - ) - - # Make the request - response = await client.generate_config_report(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.servicemanagement_v1.types.GenerateConfigReportRequest, dict]]): - The request object. Request message for - GenerateConfigReport method. - new_config (:class:`google.protobuf.any_pb2.Any`): - Required. Service configuration for which we want to - generate the report. For this version of API, the - supported types are - [google.api.servicemanagement.v1.ConfigRef][google.api.servicemanagement.v1.ConfigRef], - [google.api.servicemanagement.v1.ConfigSource][google.api.servicemanagement.v1.ConfigSource], - and [google.api.Service][google.api.Service] - - This corresponds to the ``new_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - old_config (:class:`google.protobuf.any_pb2.Any`): - Optional. Service configuration against which the - comparison will be done. For this version of API, the - supported types are - [google.api.servicemanagement.v1.ConfigRef][google.api.servicemanagement.v1.ConfigRef], - [google.api.servicemanagement.v1.ConfigSource][google.api.servicemanagement.v1.ConfigSource], - and [google.api.Service][google.api.Service] - - This corresponds to the ``old_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.cloud.servicemanagement_v1.types.GenerateConfigReportResponse: - Response message for - GenerateConfigReport method. - - """ - # Create or coerce a 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([new_config, old_config]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, servicemanager.GenerateConfigReportRequest): - request = servicemanager.GenerateConfigReportRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if new_config is not None: - request.new_config = new_config - if old_config is not None: - request.old_config = old_config - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.generate_config_report] - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self.transport._wrapped_methods[self._client._transport.list_operations] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def set_iam_policy( - self, - request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> policy_pb2.Policy: - r"""Sets the IAM access control policy on the specified function. - - Replaces any existing policy. - - Args: - request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): - The request object. Request message for `SetIamPolicy` - method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - ~.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.SetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self.transport._wrapped_methods[self._client._transport.set_iam_policy] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def get_iam_policy( - self, - request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> policy_pb2.Policy: - r"""Gets the IAM access control policy for a function. - - Returns an empty policy if the function exists and does not have a - policy set. - - Args: - request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): - The request object. Request message for `GetIamPolicy` - method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if - any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - ~.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.GetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self.transport._wrapped_methods[self._client._transport.get_iam_policy] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def test_iam_permissions( - self, - request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - r"""Tests the specified IAM permissions against the IAM access control - policy for a function. - - If the function does not exist, this will return an empty set - of permissions, not a NOT_FOUND error. - - Args: - request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): - The request object. Request message for - `TestIamPermissions` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - ~.iam_policy_pb2.TestIamPermissionsResponse: - Response message for ``TestIamPermissions`` method. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.TestIamPermissionsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self.transport._wrapped_methods[self._client._transport.test_iam_permissions] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def __aenter__(self) -> "ServiceManagerAsyncClient": - 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__ = ( - "ServiceManagerAsyncClient", -) diff --git a/owl-bot-staging/google-cloud-service-management/v1/google/cloud/servicemanagement_v1/services/service_manager/client.py b/owl-bot-staging/google-cloud-service-management/v1/google/cloud/servicemanagement_v1/services/service_manager/client.py deleted file mode 100644 index d01688cbc77d..000000000000 --- a/owl-bot-staging/google-cloud-service-management/v1/google/cloud/servicemanagement_v1/services/service_manager/client.py +++ /dev/null @@ -1,2699 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 logging as std_logging -import os -import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast -import warnings - -from google.cloud.servicemanagement_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, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - -try: - from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER -except ImportError: # pragma: NO COVER - CLIENT_LOGGING_SUPPORTED = False - -_LOGGER = std_logging.getLogger(__name__) - -from google.api import auth_pb2 # type: ignore -from google.api import backend_pb2 # type: ignore -from google.api import billing_pb2 # type: ignore -from google.api import client_pb2 # type: ignore -from google.api import context_pb2 # type: ignore -from google.api import control_pb2 # type: ignore -from google.api import documentation_pb2 # type: ignore -from google.api import endpoint_pb2 # type: ignore -from google.api import http_pb2 # type: ignore -from google.api import log_pb2 # type: ignore -from google.api import logging_pb2 # type: ignore -from google.api import metric_pb2 # type: ignore -from google.api import monitored_resource_pb2 # type: ignore -from google.api import monitoring_pb2 # type: ignore -from google.api import quota_pb2 # type: ignore -from google.api import service_pb2 # type: ignore -from google.api import source_info_pb2 # type: ignore -from google.api import system_parameter_pb2 # type: ignore -from google.api import usage_pb2 # type: ignore -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.servicemanagement_v1.services.service_manager import pagers -from google.cloud.servicemanagement_v1.types import resources -from google.cloud.servicemanagement_v1.types import servicemanager -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 any_pb2 # type: ignore -from google.protobuf import api_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import type_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore -from .transports.base import ServiceManagerTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import ServiceManagerGrpcTransport -from .transports.grpc_asyncio import ServiceManagerGrpcAsyncIOTransport -from .transports.rest import ServiceManagerRestTransport - - -class ServiceManagerClientMeta(type): - """Metaclass for the ServiceManager 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[ServiceManagerTransport]] - _transport_registry["grpc"] = ServiceManagerGrpcTransport - _transport_registry["grpc_asyncio"] = ServiceManagerGrpcAsyncIOTransport - _transport_registry["rest"] = ServiceManagerRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[ServiceManagerTransport]: - """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 ServiceManagerClient(metaclass=ServiceManagerClientMeta): - """`Google Service Management - API `__ - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = "servicemanagement.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - _DEFAULT_ENDPOINT_TEMPLATE = "servicemanagement.{UNIVERSE_DOMAIN}" - _DEFAULT_UNIVERSE = "googleapis.com" - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - ServiceManagerClient: 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: - ServiceManagerClient: 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) -> ServiceManagerTransport: - """Returns the transport used by the client instance. - - Returns: - ServiceManagerTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Deprecated. Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - - warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", - DeprecationWarning) - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - @staticmethod - def _read_environment_variables(): - """Returns the environment variables used by the client. - - Returns: - Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, - GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. - - Raises: - ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not - any of ["true", "false"]. - google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT - is not any of ["auto", "never", "always"]. - """ - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() - universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env - - @staticmethod - def _get_client_cert_source(provided_cert_source, use_cert_flag): - """Return the client cert source to be used by the client. - - Args: - provided_cert_source (bytes): The client certificate source provided. - use_cert_flag (bool): A flag indicating whether to use the client certificate. - - Returns: - bytes or None: The client cert source to be used by the client. - """ - client_cert_source = None - if use_cert_flag: - if provided_cert_source: - client_cert_source = provided_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - return client_cert_source - - @staticmethod - def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint): - """Return the API endpoint used by the client. - - Args: - api_override (str): The API endpoint override. If specified, this is always - the return value of this function and the other arguments are not used. - client_cert_source (bytes): The client certificate source used by the client. - universe_domain (str): The universe domain used by the client. - use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. - Possible values are "always", "auto", or "never". - - Returns: - str: The API endpoint to be used by the client. - """ - if api_override is not None: - api_endpoint = api_override - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - _default_universe = ServiceManagerClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = ServiceManagerClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = ServiceManagerClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=universe_domain) - return api_endpoint - - @staticmethod - def _get_universe_domain(client_universe_domain: Optional[str], universe_domain_env: Optional[str]) -> str: - """Return the universe domain used by the client. - - Args: - client_universe_domain (Optional[str]): The universe domain configured via the client options. - universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. - - Returns: - str: The universe domain to be used by the client. - - Raises: - ValueError: If the universe domain is an empty string. - """ - universe_domain = ServiceManagerClient._DEFAULT_UNIVERSE - if client_universe_domain is not None: - universe_domain = client_universe_domain - elif universe_domain_env is not None: - universe_domain = universe_domain_env - if len(universe_domain.strip()) == 0: - raise ValueError("Universe Domain cannot be an empty string.") - return universe_domain - - def _validate_universe_domain(self): - """Validates client's and credentials' universe domains are consistent. - - Returns: - bool: True iff the configured universe domain is valid. - - Raises: - ValueError: If the configured universe domain is not valid. - """ - - # NOTE (b/349488459): universe validation is disabled until further notice. - return True - - @property - def api_endpoint(self): - """Return the API endpoint used by the client instance. - - Returns: - str: The API endpoint used by the client instance. - """ - return self._api_endpoint - - @property - def universe_domain(self) -> str: - """Return the universe domain used by the client instance. - - Returns: - str: The universe domain used by the client instance. - """ - return self._universe_domain - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, ServiceManagerTransport, Callable[..., ServiceManagerTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the service manager client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Optional[Union[str,ServiceManagerTransport,Callable[..., ServiceManagerTransport]]]): - The transport to use, or a Callable that constructs and returns a new transport. - If a Callable is given, it will be called with the same set of initialization - arguments as used in the ServiceManagerTransport constructor. - If set to None, a transport is chosen automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto-switch to the - default mTLS endpoint if client certificate is present; this is - the default value). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - 3. The ``universe_domain`` property can be used to override the - default "googleapis.com" universe. Note that the ``api_endpoint`` - property still takes precedence; and ``universe_domain`` is - currently not supported for mTLS. - - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client_options = client_options - if isinstance(self._client_options, dict): - self._client_options = client_options_lib.from_dict(self._client_options) - if self._client_options is None: - self._client_options = client_options_lib.ClientOptions() - self._client_options = cast(client_options_lib.ClientOptions, self._client_options) - - universe_domain_opt = getattr(self._client_options, 'universe_domain', None) - - self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ServiceManagerClient._read_environment_variables() - self._client_cert_source = ServiceManagerClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = ServiceManagerClient._get_universe_domain(universe_domain_opt, self._universe_domain_env) - self._api_endpoint = None # updated below, depending on `transport` - - # Initialize the universe domain validation. - self._is_universe_domain_valid = False - - if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER - # Setup logging. - client_logging.initialize_logging() - - api_key_value = getattr(self._client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - transport_provided = isinstance(transport, ServiceManagerTransport) - if transport_provided: - # transport is a ServiceManagerTransport instance. - if credentials or self._client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if self._client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = cast(ServiceManagerTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - ServiceManagerClient._get_api_endpoint( - self._client_options.api_endpoint, - self._client_cert_source, - self._universe_domain, - self._use_mtls_endpoint)) - - if not transport_provided: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - transport_init: Union[Type[ServiceManagerTransport], Callable[..., ServiceManagerTransport]] = ( - ServiceManagerClient.get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., ServiceManagerTransport], transport) - ) - # initialize with the provided callable or the passed in class - self._transport = transport_init( - credentials=credentials, - credentials_file=self._client_options.credentials_file, - host=self._api_endpoint, - scopes=self._client_options.scopes, - client_cert_source_for_mtls=self._client_cert_source, - quota_project_id=self._client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=self._client_options.api_audience, - ) - - if "async" not in str(self._transport): - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG): # pragma: NO COVER - _LOGGER.debug( - "Created client `google.api.servicemanagement_v1.ServiceManagerClient`.", - extra = { - "serviceName": "google.api.servicemanagement.v1.ServiceManager", - "universeDomain": getattr(self._transport._credentials, "universe_domain", ""), - "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", - "credentialsInfo": getattr(self.transport._credentials, "get_cred_info", lambda: None)(), - } if hasattr(self._transport, "_credentials") else { - "serviceName": "google.api.servicemanagement.v1.ServiceManager", - "credentialsType": None, - } - ) - - def list_services(self, - request: Optional[Union[servicemanager.ListServicesRequest, dict]] = None, - *, - producer_project_id: Optional[str] = None, - consumer_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListServicesPager: - r"""Lists managed services. - - Returns all public services. For authenticated users, - also returns all services the calling user has - "servicemanagement.services.get" permission for. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import servicemanagement_v1 - - def sample_list_services(): - # Create a client - client = servicemanagement_v1.ServiceManagerClient() - - # Initialize request argument(s) - request = servicemanagement_v1.ListServicesRequest( - ) - - # Make the request - page_result = client.list_services(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.servicemanagement_v1.types.ListServicesRequest, dict]): - The request object. Request message for ``ListServices`` method. - producer_project_id (str): - Include services produced by the - specified project. - - This corresponds to the ``producer_project_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - consumer_id (str): - Include services consumed by the specified consumer. - - The Google Service Management implementation accepts the - following forms: - - - project: - - This corresponds to the ``consumer_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.cloud.servicemanagement_v1.services.service_manager.pagers.ListServicesPager: - Response message for ListServices method. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([producer_project_id, consumer_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.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, servicemanager.ListServicesRequest): - request = servicemanager.ListServicesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if producer_project_id is not None: - request.producer_project_id = producer_project_id - if consumer_id is not None: - request.consumer_id = consumer_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_services] - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListServicesPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_service(self, - request: Optional[Union[servicemanager.GetServiceRequest, dict]] = None, - *, - service_name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> resources.ManagedService: - r"""Gets a managed service. Authentication is required - unless the service is public. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import servicemanagement_v1 - - def sample_get_service(): - # Create a client - client = servicemanagement_v1.ServiceManagerClient() - - # Initialize request argument(s) - request = servicemanagement_v1.GetServiceRequest( - service_name="service_name_value", - ) - - # Make the request - response = client.get_service(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.servicemanagement_v1.types.GetServiceRequest, dict]): - The request object. Request message for ``GetService`` method. - service_name (str): - Required. The name of the service. See the - ``ServiceManager`` overview for naming requirements. For - example: ``example.googleapis.com``. - - This corresponds to the ``service_name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.cloud.servicemanagement_v1.types.ManagedService: - The full representation of a Service - that is managed by Google Service - Management. - - """ - # Create or coerce a 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([service_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.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, servicemanager.GetServiceRequest): - request = servicemanager.GetServiceRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if service_name is not None: - request.service_name = service_name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_service] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("service_name", request.service_name), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def create_service(self, - request: Optional[Union[servicemanager.CreateServiceRequest, dict]] = None, - *, - service: Optional[resources.ManagedService] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: - r"""Creates a new managed service. - - A managed service is immutable, and is subject to - mandatory 30-day data retention. You cannot move a - service or recreate it within 30 days after deletion. - - One producer project can own no more than 500 services. - For security and reliability purposes, a production - service should be hosted in a dedicated producer - project. - - Operation - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import servicemanagement_v1 - - def sample_create_service(): - # Create a client - client = servicemanagement_v1.ServiceManagerClient() - - # Initialize request argument(s) - request = servicemanagement_v1.CreateServiceRequest( - ) - - # Make the request - operation = client.create_service(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.servicemanagement_v1.types.CreateServiceRequest, dict]): - The request object. Request message for CreateService - method. - service (google.cloud.servicemanagement_v1.types.ManagedService): - Required. Initial values for the - service resource. - - This corresponds to the ``service`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.servicemanagement_v1.types.ManagedService` The full representation of a Service that is managed by - Google Service Management. - - """ - # Create or coerce a 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([service]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, servicemanager.CreateServiceRequest): - request = servicemanager.CreateServiceRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if service is not None: - request.service = service - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_service] - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - resources.ManagedService, - metadata_type=resources.OperationMetadata, - ) - - # Done; return the response. - return response - - def delete_service(self, - request: Optional[Union[servicemanager.DeleteServiceRequest, dict]] = None, - *, - service_name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: - r"""Deletes a managed service. This method will change the service - to the ``Soft-Delete`` state for 30 days. Within this period, - service producers may call - [UndeleteService][google.api.servicemanagement.v1.ServiceManager.UndeleteService] - to restore the service. After 30 days, the service will be - permanently deleted. - - Operation - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import servicemanagement_v1 - - def sample_delete_service(): - # Create a client - client = servicemanagement_v1.ServiceManagerClient() - - # Initialize request argument(s) - request = servicemanagement_v1.DeleteServiceRequest( - service_name="service_name_value", - ) - - # Make the request - operation = client.delete_service(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.servicemanagement_v1.types.DeleteServiceRequest, dict]): - The request object. Request message for DeleteService - method. - service_name (str): - Required. The name of the service. See the - `overview `__ - for naming requirements. For example: - ``example.googleapis.com``. - - This corresponds to the ``service_name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([service_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.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, servicemanager.DeleteServiceRequest): - request = servicemanager.DeleteServiceRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if service_name is not None: - request.service_name = service_name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_service] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("service_name", request.service_name), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - empty_pb2.Empty, - metadata_type=resources.OperationMetadata, - ) - - # Done; return the response. - return response - - def undelete_service(self, - request: Optional[Union[servicemanager.UndeleteServiceRequest, dict]] = None, - *, - service_name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: - r"""Revives a previously deleted managed service. The - method restores the service using the configuration at - the time the service was deleted. The target service - must exist and must have been deleted within the last 30 - days. - - Operation - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import servicemanagement_v1 - - def sample_undelete_service(): - # Create a client - client = servicemanagement_v1.ServiceManagerClient() - - # Initialize request argument(s) - request = servicemanagement_v1.UndeleteServiceRequest( - service_name="service_name_value", - ) - - # Make the request - operation = client.undelete_service(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.servicemanagement_v1.types.UndeleteServiceRequest, dict]): - The request object. Request message for UndeleteService - method. - service_name (str): - Required. The name of the service. See the - `overview `__ - for naming requirements. For example: - ``example.googleapis.com``. - - This corresponds to the ``service_name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.servicemanagement_v1.types.UndeleteServiceResponse` - Response message for UndeleteService method. - - """ - # Create or coerce a 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([service_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.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, servicemanager.UndeleteServiceRequest): - request = servicemanager.UndeleteServiceRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if service_name is not None: - request.service_name = service_name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.undelete_service] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("service_name", request.service_name), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - servicemanager.UndeleteServiceResponse, - metadata_type=resources.OperationMetadata, - ) - - # Done; return the response. - return response - - def list_service_configs(self, - request: Optional[Union[servicemanager.ListServiceConfigsRequest, dict]] = None, - *, - service_name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListServiceConfigsPager: - r"""Lists the history of the service configuration for a - managed service, from the newest to the oldest. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import servicemanagement_v1 - - def sample_list_service_configs(): - # Create a client - client = servicemanagement_v1.ServiceManagerClient() - - # Initialize request argument(s) - request = servicemanagement_v1.ListServiceConfigsRequest( - service_name="service_name_value", - ) - - # Make the request - page_result = client.list_service_configs(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.servicemanagement_v1.types.ListServiceConfigsRequest, dict]): - The request object. Request message for - ListServiceConfigs method. - service_name (str): - Required. The name of the service. See the - `overview `__ - for naming requirements. For example: - ``example.googleapis.com``. - - This corresponds to the ``service_name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.cloud.servicemanagement_v1.services.service_manager.pagers.ListServiceConfigsPager: - Response message for - ListServiceConfigs method. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([service_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.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, servicemanager.ListServiceConfigsRequest): - request = servicemanager.ListServiceConfigsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if service_name is not None: - request.service_name = service_name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_service_configs] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("service_name", request.service_name), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListServiceConfigsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_service_config(self, - request: Optional[Union[servicemanager.GetServiceConfigRequest, dict]] = None, - *, - service_name: Optional[str] = None, - config_id: Optional[str] = None, - view: Optional[servicemanager.GetServiceConfigRequest.ConfigView] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> service_pb2.Service: - r"""Gets a service configuration (version) for a managed - service. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import servicemanagement_v1 - - def sample_get_service_config(): - # Create a client - client = servicemanagement_v1.ServiceManagerClient() - - # Initialize request argument(s) - request = servicemanagement_v1.GetServiceConfigRequest( - service_name="service_name_value", - config_id="config_id_value", - ) - - # Make the request - response = client.get_service_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.servicemanagement_v1.types.GetServiceConfigRequest, dict]): - The request object. Request message for GetServiceConfig - method. - service_name (str): - Required. The name of the service. See the - `overview `__ - for naming requirements. For example: - ``example.googleapis.com``. - - This corresponds to the ``service_name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - config_id (str): - Required. The id of the service configuration resource. - - This field must be specified for the server to return - all fields, including ``SourceInfo``. - - This corresponds to the ``config_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - view (google.cloud.servicemanagement_v1.types.GetServiceConfigRequest.ConfigView): - Specifies which parts of the Service - Config should be returned in the - response. - - This corresponds to the ``view`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.api.service_pb2.Service: - Service is the root object of Google API service configuration (service - config). It describes the basic information about a - logical service, such as the service name and the - user-facing title, and delegates other aspects to - sub-sections. Each sub-section is either a proto - message or a repeated proto message that configures a - specific aspect, such as auth. For more information, - see each proto message definition. - - Example: - - type: google.api.Service name: - calendar.googleapis.com title: Google Calendar API - apis: - name: google.calendar.v3.Calendar - - visibility: - rules: - selector: "google.calendar.v3.*" - restriction: PREVIEW - - backend: - rules: - selector: "google.calendar.v3.*" - address: calendar.example.com - - authentication: - providers: - id: google_calendar_auth jwks_uri: - https://www.googleapis.com/oauth2/v1/certs - issuer: https://securetoken.google.com rules: - - selector: "*" requirements: provider_id: - google_calendar_auth - - """ - # Create or coerce a 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([service_name, config_id, view]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, servicemanager.GetServiceConfigRequest): - request = servicemanager.GetServiceConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if service_name is not None: - request.service_name = service_name - if config_id is not None: - request.config_id = config_id - if view is not None: - request.view = view - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_service_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("service_name", request.service_name), - ("config_id", request.config_id), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def create_service_config(self, - request: Optional[Union[servicemanager.CreateServiceConfigRequest, dict]] = None, - *, - service_name: Optional[str] = None, - service_config: Optional[service_pb2.Service] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> service_pb2.Service: - r"""Creates a new service configuration (version) for a managed - service. This method only stores the service configuration. To - roll out the service configuration to backend systems please - call - [CreateServiceRollout][google.api.servicemanagement.v1.ServiceManager.CreateServiceRollout]. - - Only the 100 most recent service configurations and ones - referenced by existing rollouts are kept for each service. The - rest will be deleted eventually. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import servicemanagement_v1 - - def sample_create_service_config(): - # Create a client - client = servicemanagement_v1.ServiceManagerClient() - - # Initialize request argument(s) - request = servicemanagement_v1.CreateServiceConfigRequest( - service_name="service_name_value", - ) - - # Make the request - response = client.create_service_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.servicemanagement_v1.types.CreateServiceConfigRequest, dict]): - The request object. Request message for - CreateServiceConfig method. - service_name (str): - Required. The name of the service. See the - `overview `__ - for naming requirements. For example: - ``example.googleapis.com``. - - This corresponds to the ``service_name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - service_config (google.api.service_pb2.Service): - Required. The service configuration - resource. - - This corresponds to the ``service_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.api.service_pb2.Service: - Service is the root object of Google API service configuration (service - config). It describes the basic information about a - logical service, such as the service name and the - user-facing title, and delegates other aspects to - sub-sections. Each sub-section is either a proto - message or a repeated proto message that configures a - specific aspect, such as auth. For more information, - see each proto message definition. - - Example: - - type: google.api.Service name: - calendar.googleapis.com title: Google Calendar API - apis: - name: google.calendar.v3.Calendar - - visibility: - rules: - selector: "google.calendar.v3.*" - restriction: PREVIEW - - backend: - rules: - selector: "google.calendar.v3.*" - address: calendar.example.com - - authentication: - providers: - id: google_calendar_auth jwks_uri: - https://www.googleapis.com/oauth2/v1/certs - issuer: https://securetoken.google.com rules: - - selector: "*" requirements: provider_id: - google_calendar_auth - - """ - # Create or coerce a 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([service_name, service_config]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, servicemanager.CreateServiceConfigRequest): - request = servicemanager.CreateServiceConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if service_name is not None: - request.service_name = service_name - if service_config is not None: - request.service_config = service_config - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_service_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("service_name", request.service_name), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def submit_config_source(self, - request: Optional[Union[servicemanager.SubmitConfigSourceRequest, dict]] = None, - *, - service_name: Optional[str] = None, - config_source: Optional[resources.ConfigSource] = None, - validate_only: Optional[bool] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: - r"""Creates a new service configuration (version) for a managed - service based on user-supplied configuration source files (for - example: OpenAPI Specification). This method stores the source - configurations as well as the generated service configuration. - To rollout the service configuration to other services, please - call - [CreateServiceRollout][google.api.servicemanagement.v1.ServiceManager.CreateServiceRollout]. - - Only the 100 most recent configuration sources and ones - referenced by existing service configurtions are kept for each - service. The rest will be deleted eventually. - - Operation - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import servicemanagement_v1 - - def sample_submit_config_source(): - # Create a client - client = servicemanagement_v1.ServiceManagerClient() - - # Initialize request argument(s) - request = servicemanagement_v1.SubmitConfigSourceRequest( - service_name="service_name_value", - ) - - # Make the request - operation = client.submit_config_source(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.servicemanagement_v1.types.SubmitConfigSourceRequest, dict]): - The request object. Request message for - SubmitConfigSource method. - service_name (str): - Required. The name of the service. See the - `overview `__ - for naming requirements. For example: - ``example.googleapis.com``. - - This corresponds to the ``service_name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - config_source (google.cloud.servicemanagement_v1.types.ConfigSource): - Required. The source configuration - for the service. - - This corresponds to the ``config_source`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - validate_only (bool): - Optional. If set, this will result in the generation of - a ``google.api.Service`` configuration based on the - ``ConfigSource`` provided, but the generated config and - the sources will NOT be persisted. - - This corresponds to the ``validate_only`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.servicemanagement_v1.types.SubmitConfigSourceResponse` - Response message for SubmitConfigSource method. - - """ - # Create or coerce a 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([service_name, config_source, validate_only]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, servicemanager.SubmitConfigSourceRequest): - request = servicemanager.SubmitConfigSourceRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if service_name is not None: - request.service_name = service_name - if config_source is not None: - request.config_source = config_source - if validate_only is not None: - request.validate_only = validate_only - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.submit_config_source] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("service_name", request.service_name), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - servicemanager.SubmitConfigSourceResponse, - metadata_type=resources.OperationMetadata, - ) - - # Done; return the response. - return response - - def list_service_rollouts(self, - request: Optional[Union[servicemanager.ListServiceRolloutsRequest, dict]] = None, - *, - service_name: Optional[str] = None, - filter: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListServiceRolloutsPager: - r"""Lists the history of the service configuration - rollouts for a managed service, from the newest to the - oldest. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import servicemanagement_v1 - - def sample_list_service_rollouts(): - # Create a client - client = servicemanagement_v1.ServiceManagerClient() - - # Initialize request argument(s) - request = servicemanagement_v1.ListServiceRolloutsRequest( - service_name="service_name_value", - filter="filter_value", - ) - - # Make the request - page_result = client.list_service_rollouts(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.servicemanagement_v1.types.ListServiceRolloutsRequest, dict]): - The request object. Request message for - 'ListServiceRollouts' - service_name (str): - Required. The name of the service. See the - `overview `__ - for naming requirements. For example: - ``example.googleapis.com``. - - This corresponds to the ``service_name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - filter (str): - Required. Use ``filter`` to return subset of rollouts. - The following filters are supported: - - -- By [status] - [google.api.servicemanagement.v1.Rollout.RolloutStatus]. - For example, ``filter='status=SUCCESS'`` - - -- By [strategy] - [google.api.servicemanagement.v1.Rollout.strategy]. For - example, ``filter='strategy=TrafficPercentStrategy'`` - - This corresponds to the ``filter`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.cloud.servicemanagement_v1.services.service_manager.pagers.ListServiceRolloutsPager: - Response message for - ListServiceRollouts method. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([service_name, filter]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, servicemanager.ListServiceRolloutsRequest): - request = servicemanager.ListServiceRolloutsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if service_name is not None: - request.service_name = service_name - if filter is not None: - request.filter = filter - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_service_rollouts] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("service_name", request.service_name), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListServiceRolloutsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_service_rollout(self, - request: Optional[Union[servicemanager.GetServiceRolloutRequest, dict]] = None, - *, - service_name: Optional[str] = None, - rollout_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> resources.Rollout: - r"""Gets a service configuration - [rollout][google.api.servicemanagement.v1.Rollout]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import servicemanagement_v1 - - def sample_get_service_rollout(): - # Create a client - client = servicemanagement_v1.ServiceManagerClient() - - # Initialize request argument(s) - request = servicemanagement_v1.GetServiceRolloutRequest( - service_name="service_name_value", - rollout_id="rollout_id_value", - ) - - # Make the request - response = client.get_service_rollout(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.servicemanagement_v1.types.GetServiceRolloutRequest, dict]): - The request object. Request message for GetServiceRollout - method. - service_name (str): - Required. The name of the service. See the - `overview `__ - for naming requirements. For example: - ``example.googleapis.com``. - - This corresponds to the ``service_name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - rollout_id (str): - Required. The id of the rollout - resource. - - This corresponds to the ``rollout_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.cloud.servicemanagement_v1.types.Rollout: - A rollout resource that defines how - service configuration versions are - pushed to control plane systems. - Typically, you create a new version of - the service config, and then create a - Rollout to push the service config. - - """ - # Create or coerce a 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([service_name, rollout_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.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, servicemanager.GetServiceRolloutRequest): - request = servicemanager.GetServiceRolloutRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if service_name is not None: - request.service_name = service_name - if rollout_id is not None: - request.rollout_id = rollout_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_service_rollout] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("service_name", request.service_name), - ("rollout_id", request.rollout_id), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def create_service_rollout(self, - request: Optional[Union[servicemanager.CreateServiceRolloutRequest, dict]] = None, - *, - service_name: Optional[str] = None, - rollout: Optional[resources.Rollout] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operation.Operation: - r"""Creates a new service configuration rollout. Based on - rollout, the Google Service Management will roll out the - service configurations to different backend services. - For example, the logging configuration will be pushed to - Google Cloud Logging. - - Please note that any previous pending and running - Rollouts and associated Operations will be automatically - cancelled so that the latest Rollout will not be blocked - by previous Rollouts. - - Only the 100 most recent (in any state) and the last 10 - successful (if not already part of the set of 100 most - recent) rollouts are kept for each service. The rest - will be deleted eventually. - - Operation - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import servicemanagement_v1 - - def sample_create_service_rollout(): - # Create a client - client = servicemanagement_v1.ServiceManagerClient() - - # Initialize request argument(s) - request = servicemanagement_v1.CreateServiceRolloutRequest( - service_name="service_name_value", - ) - - # Make the request - operation = client.create_service_rollout(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.servicemanagement_v1.types.CreateServiceRolloutRequest, dict]): - The request object. Request message for - 'CreateServiceRollout' - service_name (str): - Required. The name of the service. See the - `overview `__ - for naming requirements. For example: - ``example.googleapis.com``. - - This corresponds to the ``service_name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - rollout (google.cloud.servicemanagement_v1.types.Rollout): - Required. The rollout resource. The ``service_name`` - field is output only. - - This corresponds to the ``rollout`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.servicemanagement_v1.types.Rollout` A rollout resource that defines how service configuration versions are pushed - to control plane systems. Typically, you create a new - version of the service config, and then create a - Rollout to push the service config. - - """ - # Create or coerce a 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([service_name, rollout]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, servicemanager.CreateServiceRolloutRequest): - request = servicemanager.CreateServiceRolloutRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if service_name is not None: - request.service_name = service_name - if rollout is not None: - request.rollout = rollout - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_service_rollout] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("service_name", request.service_name), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - resources.Rollout, - metadata_type=resources.OperationMetadata, - ) - - # Done; return the response. - return response - - def generate_config_report(self, - request: Optional[Union[servicemanager.GenerateConfigReportRequest, dict]] = None, - *, - new_config: Optional[any_pb2.Any] = None, - old_config: Optional[any_pb2.Any] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> servicemanager.GenerateConfigReportResponse: - r"""Generates and returns a report (errors, warnings and changes - from existing configurations) associated with - GenerateConfigReportRequest.new_value - - If GenerateConfigReportRequest.old_value is specified, - GenerateConfigReportRequest will contain a single ChangeReport - based on the comparison between - GenerateConfigReportRequest.new_value and - GenerateConfigReportRequest.old_value. If - GenerateConfigReportRequest.old_value is not specified, this - method will compare GenerateConfigReportRequest.new_value with - the last pushed service configuration. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import servicemanagement_v1 - - def sample_generate_config_report(): - # Create a client - client = servicemanagement_v1.ServiceManagerClient() - - # Initialize request argument(s) - request = servicemanagement_v1.GenerateConfigReportRequest( - ) - - # Make the request - response = client.generate_config_report(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.servicemanagement_v1.types.GenerateConfigReportRequest, dict]): - The request object. Request message for - GenerateConfigReport method. - new_config (google.protobuf.any_pb2.Any): - Required. Service configuration for which we want to - generate the report. For this version of API, the - supported types are - [google.api.servicemanagement.v1.ConfigRef][google.api.servicemanagement.v1.ConfigRef], - [google.api.servicemanagement.v1.ConfigSource][google.api.servicemanagement.v1.ConfigSource], - and [google.api.Service][google.api.Service] - - This corresponds to the ``new_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - old_config (google.protobuf.any_pb2.Any): - Optional. Service configuration against which the - comparison will be done. For this version of API, the - supported types are - [google.api.servicemanagement.v1.ConfigRef][google.api.servicemanagement.v1.ConfigRef], - [google.api.servicemanagement.v1.ConfigSource][google.api.servicemanagement.v1.ConfigSource], - and [google.api.Service][google.api.Service] - - This corresponds to the ``old_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - google.cloud.servicemanagement_v1.types.GenerateConfigReportResponse: - Response message for - GenerateConfigReport method. - - """ - # Create or coerce a 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([new_config, old_config]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, servicemanager.GenerateConfigReportRequest): - request = servicemanager.GenerateConfigReportRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if new_config is not None: - request.new_config = new_config - if old_config is not None: - request.old_config = old_config - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.generate_config_report] - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "ServiceManagerClient": - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_operations] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def set_iam_policy( - self, - request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> policy_pb2.Policy: - r"""Sets the IAM access control policy on the specified function. - - Replaces any existing policy. - - Args: - request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): - The request object. Request message for `SetIamPolicy` - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - ~.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.SetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.set_iam_policy] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # 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, Union[str, bytes]]] = (), - ) -> policy_pb2.Policy: - r"""Gets the IAM access control policy for a function. - - Returns an empty policy if the function exists and does not have a - policy set. - - Args: - request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): - The request object. Request message for `GetIamPolicy` - method. - retry (google.api_core.retry.Retry): Designation of what errors, if - any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - ~.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.GetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_iam_policy] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # 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, Union[str, bytes]]] = (), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - r"""Tests the specified IAM permissions against the IAM access control - policy for a function. - - If the function does not exist, this will return an empty set - of permissions, not a NOT_FOUND error. - - Args: - request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): - The request object. Request message for - `TestIamPermissions` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - Returns: - ~.iam_policy_pb2.TestIamPermissionsResponse: - Response message for ``TestIamPermissions`` method. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.TestIamPermissionsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.test_iam_permissions] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # 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__ = ( - "ServiceManagerClient", -) diff --git a/owl-bot-staging/google-cloud-service-management/v1/google/cloud/servicemanagement_v1/services/service_manager/pagers.py b/owl-bot-staging/google-cloud-service-management/v1/google/cloud/servicemanagement_v1/services/service_manager/pagers.py deleted file mode 100644 index e3b25c1e6705..000000000000 --- a/owl-bot-staging/google-cloud-service-management/v1/google/cloud/servicemanagement_v1/services/service_manager/pagers.py +++ /dev/null @@ -1,446 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.api_core import retry_async as retries_async -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator, Union -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] - OptionalAsyncRetry = Union[retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore - -from google.api import service_pb2 # type: ignore -from google.cloud.servicemanagement_v1.types import resources -from google.cloud.servicemanagement_v1.types import servicemanager - - -class ListServicesPager: - """A pager for iterating through ``list_services`` requests. - - This class thinly wraps an initial - :class:`google.cloud.servicemanagement_v1.types.ListServicesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``services`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListServices`` requests and continue to iterate - through the ``services`` field on the - corresponding responses. - - All the usual :class:`google.cloud.servicemanagement_v1.types.ListServicesResponse` - 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[..., servicemanager.ListServicesResponse], - request: servicemanager.ListServicesRequest, - response: servicemanager.ListServicesResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.servicemanagement_v1.types.ListServicesRequest): - The initial request object. - response (google.cloud.servicemanagement_v1.types.ListServicesResponse): - The initial response object. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - self._method = method - self._request = servicemanager.ListServicesRequest(request) - self._response = response - self._retry = retry - self._timeout = timeout - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[servicemanager.ListServicesResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[resources.ManagedService]: - for page in self.pages: - yield from page.services - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListServicesAsyncPager: - """A pager for iterating through ``list_services`` requests. - - This class thinly wraps an initial - :class:`google.cloud.servicemanagement_v1.types.ListServicesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``services`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListServices`` requests and continue to iterate - through the ``services`` field on the - corresponding responses. - - All the usual :class:`google.cloud.servicemanagement_v1.types.ListServicesResponse` - 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[servicemanager.ListServicesResponse]], - request: servicemanager.ListServicesRequest, - response: servicemanager.ListServicesResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.servicemanagement_v1.types.ListServicesRequest): - The initial request object. - response (google.cloud.servicemanagement_v1.types.ListServicesResponse): - The initial response object. - retry (google.api_core.retry.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - self._method = method - self._request = servicemanager.ListServicesRequest(request) - self._response = response - self._retry = retry - self._timeout = timeout - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[servicemanager.ListServicesResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[resources.ManagedService]: - async def async_generator(): - async for page in self.pages: - for response in page.services: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListServiceConfigsPager: - """A pager for iterating through ``list_service_configs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.servicemanagement_v1.types.ListServiceConfigsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``service_configs`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListServiceConfigs`` requests and continue to iterate - through the ``service_configs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.servicemanagement_v1.types.ListServiceConfigsResponse` - 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[..., servicemanager.ListServiceConfigsResponse], - request: servicemanager.ListServiceConfigsRequest, - response: servicemanager.ListServiceConfigsResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.servicemanagement_v1.types.ListServiceConfigsRequest): - The initial request object. - response (google.cloud.servicemanagement_v1.types.ListServiceConfigsResponse): - The initial response object. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - self._method = method - self._request = servicemanager.ListServiceConfigsRequest(request) - self._response = response - self._retry = retry - self._timeout = timeout - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[servicemanager.ListServiceConfigsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[service_pb2.Service]: - for page in self.pages: - yield from page.service_configs - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListServiceConfigsAsyncPager: - """A pager for iterating through ``list_service_configs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.servicemanagement_v1.types.ListServiceConfigsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``service_configs`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListServiceConfigs`` requests and continue to iterate - through the ``service_configs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.servicemanagement_v1.types.ListServiceConfigsResponse` - 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[servicemanager.ListServiceConfigsResponse]], - request: servicemanager.ListServiceConfigsRequest, - response: servicemanager.ListServiceConfigsResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.servicemanagement_v1.types.ListServiceConfigsRequest): - The initial request object. - response (google.cloud.servicemanagement_v1.types.ListServiceConfigsResponse): - The initial response object. - retry (google.api_core.retry.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - self._method = method - self._request = servicemanager.ListServiceConfigsRequest(request) - self._response = response - self._retry = retry - self._timeout = timeout - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[servicemanager.ListServiceConfigsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[service_pb2.Service]: - async def async_generator(): - async for page in self.pages: - for response in page.service_configs: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListServiceRolloutsPager: - """A pager for iterating through ``list_service_rollouts`` requests. - - This class thinly wraps an initial - :class:`google.cloud.servicemanagement_v1.types.ListServiceRolloutsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``rollouts`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListServiceRollouts`` requests and continue to iterate - through the ``rollouts`` field on the - corresponding responses. - - All the usual :class:`google.cloud.servicemanagement_v1.types.ListServiceRolloutsResponse` - 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[..., servicemanager.ListServiceRolloutsResponse], - request: servicemanager.ListServiceRolloutsRequest, - response: servicemanager.ListServiceRolloutsResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.servicemanagement_v1.types.ListServiceRolloutsRequest): - The initial request object. - response (google.cloud.servicemanagement_v1.types.ListServiceRolloutsResponse): - The initial response object. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - self._method = method - self._request = servicemanager.ListServiceRolloutsRequest(request) - self._response = response - self._retry = retry - self._timeout = timeout - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[servicemanager.ListServiceRolloutsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[resources.Rollout]: - for page in self.pages: - yield from page.rollouts - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListServiceRolloutsAsyncPager: - """A pager for iterating through ``list_service_rollouts`` requests. - - This class thinly wraps an initial - :class:`google.cloud.servicemanagement_v1.types.ListServiceRolloutsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``rollouts`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListServiceRollouts`` requests and continue to iterate - through the ``rollouts`` field on the - corresponding responses. - - All the usual :class:`google.cloud.servicemanagement_v1.types.ListServiceRolloutsResponse` - 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[servicemanager.ListServiceRolloutsResponse]], - request: servicemanager.ListServiceRolloutsRequest, - response: servicemanager.ListServiceRolloutsResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.servicemanagement_v1.types.ListServiceRolloutsRequest): - The initial request object. - response (google.cloud.servicemanagement_v1.types.ListServiceRolloutsResponse): - The initial response object. - retry (google.api_core.retry.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - """ - self._method = method - self._request = servicemanager.ListServiceRolloutsRequest(request) - self._response = response - self._retry = retry - self._timeout = timeout - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[servicemanager.ListServiceRolloutsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[resources.Rollout]: - async def async_generator(): - async for page in self.pages: - for response in page.rollouts: - 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-service-management/v1/google/cloud/servicemanagement_v1/services/service_manager/transports/README.rst b/owl-bot-staging/google-cloud-service-management/v1/google/cloud/servicemanagement_v1/services/service_manager/transports/README.rst deleted file mode 100644 index 39f819d78267..000000000000 --- a/owl-bot-staging/google-cloud-service-management/v1/google/cloud/servicemanagement_v1/services/service_manager/transports/README.rst +++ /dev/null @@ -1,9 +0,0 @@ - -transport inheritance structure -_______________________________ - -`ServiceManagerTransport` is the ABC for all transports. -- public child `ServiceManagerGrpcTransport` for sync gRPC transport (defined in `grpc.py`). -- public child `ServiceManagerGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). -- private child `_BaseServiceManagerRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). -- public child `ServiceManagerRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/owl-bot-staging/google-cloud-service-management/v1/google/cloud/servicemanagement_v1/services/service_manager/transports/__init__.py b/owl-bot-staging/google-cloud-service-management/v1/google/cloud/servicemanagement_v1/services/service_manager/transports/__init__.py deleted file mode 100644 index c2df30ff9129..000000000000 --- a/owl-bot-staging/google-cloud-service-management/v1/google/cloud/servicemanagement_v1/services/service_manager/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 ServiceManagerTransport -from .grpc import ServiceManagerGrpcTransport -from .grpc_asyncio import ServiceManagerGrpcAsyncIOTransport -from .rest import ServiceManagerRestTransport -from .rest import ServiceManagerRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[ServiceManagerTransport]] -_transport_registry['grpc'] = ServiceManagerGrpcTransport -_transport_registry['grpc_asyncio'] = ServiceManagerGrpcAsyncIOTransport -_transport_registry['rest'] = ServiceManagerRestTransport - -__all__ = ( - 'ServiceManagerTransport', - 'ServiceManagerGrpcTransport', - 'ServiceManagerGrpcAsyncIOTransport', - 'ServiceManagerRestTransport', - 'ServiceManagerRestInterceptor', -) diff --git a/owl-bot-staging/google-cloud-service-management/v1/google/cloud/servicemanagement_v1/services/service_manager/transports/base.py b/owl-bot-staging/google-cloud-service-management/v1/google/cloud/servicemanagement_v1/services/service_manager/transports/base.py deleted file mode 100644 index 864031ae421a..000000000000 --- a/owl-bot-staging/google-cloud-service-management/v1/google/cloud/servicemanagement_v1/services/service_manager/transports/base.py +++ /dev/null @@ -1,395 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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.servicemanagement_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.api import service_pb2 # type: ignore -from google.cloud.servicemanagement_v1.types import resources -from google.cloud.servicemanagement_v1.types import servicemanager -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 - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class ServiceManagerTransport(abc.ABC): - """Abstract transport class for ServiceManager.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', - 'https://www.googleapis.com/auth/service.management', - 'https://www.googleapis.com/auth/service.management.readonly', - ) - - DEFAULT_HOST: str = 'servicemanagement.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'servicemanagement.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - if not hasattr(self, "_ignore_credentials"): - self._ignore_credentials: bool = False - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None and not self._ignore_credentials: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - @property - def host(self): - return self._host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.list_services: gapic_v1.method.wrap_method( - self.list_services, - default_timeout=None, - client_info=client_info, - ), - self.get_service: gapic_v1.method.wrap_method( - self.get_service, - default_timeout=None, - client_info=client_info, - ), - self.create_service: gapic_v1.method.wrap_method( - self.create_service, - default_timeout=None, - client_info=client_info, - ), - self.delete_service: gapic_v1.method.wrap_method( - self.delete_service, - default_timeout=None, - client_info=client_info, - ), - self.undelete_service: gapic_v1.method.wrap_method( - self.undelete_service, - default_timeout=None, - client_info=client_info, - ), - self.list_service_configs: gapic_v1.method.wrap_method( - self.list_service_configs, - default_timeout=None, - client_info=client_info, - ), - self.get_service_config: gapic_v1.method.wrap_method( - self.get_service_config, - default_timeout=None, - client_info=client_info, - ), - self.create_service_config: gapic_v1.method.wrap_method( - self.create_service_config, - default_timeout=None, - client_info=client_info, - ), - self.submit_config_source: gapic_v1.method.wrap_method( - self.submit_config_source, - default_timeout=None, - client_info=client_info, - ), - self.list_service_rollouts: gapic_v1.method.wrap_method( - self.list_service_rollouts, - default_timeout=None, - client_info=client_info, - ), - self.get_service_rollout: gapic_v1.method.wrap_method( - self.get_service_rollout, - default_timeout=None, - client_info=client_info, - ), - self.create_service_rollout: gapic_v1.method.wrap_method( - self.create_service_rollout, - default_timeout=None, - client_info=client_info, - ), - self.generate_config_report: gapic_v1.method.wrap_method( - self.generate_config_report, - default_timeout=None, - client_info=client_info, - ), - self.get_iam_policy: gapic_v1.method.wrap_method( - self.get_iam_policy, - default_timeout=None, - client_info=client_info, - ), - self.set_iam_policy: gapic_v1.method.wrap_method( - self.set_iam_policy, - default_timeout=None, - client_info=client_info, - ), - self.test_iam_permissions: gapic_v1.method.wrap_method( - self.test_iam_permissions, - default_timeout=None, - client_info=client_info, - ), - self.list_operations: gapic_v1.method.wrap_method( - self.list_operations, - default_timeout=None, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def operations_client(self): - """Return the client designed to process long-running operations.""" - raise NotImplementedError() - - @property - def list_services(self) -> Callable[ - [servicemanager.ListServicesRequest], - Union[ - servicemanager.ListServicesResponse, - Awaitable[servicemanager.ListServicesResponse] - ]]: - raise NotImplementedError() - - @property - def get_service(self) -> Callable[ - [servicemanager.GetServiceRequest], - Union[ - resources.ManagedService, - Awaitable[resources.ManagedService] - ]]: - raise NotImplementedError() - - @property - def create_service(self) -> Callable[ - [servicemanager.CreateServiceRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def delete_service(self) -> Callable[ - [servicemanager.DeleteServiceRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def undelete_service(self) -> Callable[ - [servicemanager.UndeleteServiceRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def list_service_configs(self) -> Callable[ - [servicemanager.ListServiceConfigsRequest], - Union[ - servicemanager.ListServiceConfigsResponse, - Awaitable[servicemanager.ListServiceConfigsResponse] - ]]: - raise NotImplementedError() - - @property - def get_service_config(self) -> Callable[ - [servicemanager.GetServiceConfigRequest], - Union[ - service_pb2.Service, - Awaitable[service_pb2.Service] - ]]: - raise NotImplementedError() - - @property - def create_service_config(self) -> Callable[ - [servicemanager.CreateServiceConfigRequest], - Union[ - service_pb2.Service, - Awaitable[service_pb2.Service] - ]]: - raise NotImplementedError() - - @property - def submit_config_source(self) -> Callable[ - [servicemanager.SubmitConfigSourceRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def list_service_rollouts(self) -> Callable[ - [servicemanager.ListServiceRolloutsRequest], - Union[ - servicemanager.ListServiceRolloutsResponse, - Awaitable[servicemanager.ListServiceRolloutsResponse] - ]]: - raise NotImplementedError() - - @property - def get_service_rollout(self) -> Callable[ - [servicemanager.GetServiceRolloutRequest], - Union[ - resources.Rollout, - Awaitable[resources.Rollout] - ]]: - raise NotImplementedError() - - @property - def create_service_rollout(self) -> Callable[ - [servicemanager.CreateServiceRolloutRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def generate_config_report(self) -> Callable[ - [servicemanager.GenerateConfigReportRequest], - Union[ - servicemanager.GenerateConfigReportResponse, - Awaitable[servicemanager.GenerateConfigReportResponse] - ]]: - raise NotImplementedError() - - @property - def list_operations( - self, - ) -> Callable[ - [operations_pb2.ListOperationsRequest], - Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], - ]: - 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 kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'ServiceManagerTransport', -) diff --git a/owl-bot-staging/google-cloud-service-management/v1/google/cloud/servicemanagement_v1/services/service_manager/transports/grpc.py b/owl-bot-staging/google-cloud-service-management/v1/google/cloud/servicemanagement_v1/services/service_manager/transports/grpc.py deleted file mode 100644 index 7718bdd798cb..000000000000 --- a/owl-bot-staging/google-cloud-service-management/v1/google/cloud/servicemanagement_v1/services/service_manager/transports/grpc.py +++ /dev/null @@ -1,861 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import json -import logging as std_logging -import pickle -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import operations_v1 -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.protobuf.json_format import MessageToJson -import google.protobuf.message - -import grpc # type: ignore -import proto # type: ignore - -from google.api import service_pb2 # type: ignore -from google.cloud.servicemanagement_v1.types import resources -from google.cloud.servicemanagement_v1.types import servicemanager -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 .base import ServiceManagerTransport, DEFAULT_CLIENT_INFO - -try: - from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER -except ImportError: # pragma: NO COVER - CLIENT_LOGGING_SUPPORTED = False - -_LOGGER = std_logging.getLogger(__name__) - - -class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER - def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) - if logging_enabled: # pragma: NO COVER - request_metadata = client_call_details.metadata - if isinstance(request, proto.Message): - request_payload = type(request).to_json(request) - elif isinstance(request, google.protobuf.message.Message): - request_payload = MessageToJson(request) - else: - request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" - - request_metadata = { - key: value.decode("utf-8") if isinstance(value, bytes) else value - for key, value in request_metadata - } - grpc_request = { - "payload": request_payload, - "requestMethod": "grpc", - "metadata": dict(request_metadata), - } - _LOGGER.debug( - f"Sending request for {client_call_details.method}", - extra = { - "serviceName": "google.api.servicemanagement.v1.ServiceManager", - "rpcName": client_call_details.method, - "request": grpc_request, - "metadata": grpc_request["metadata"], - }, - ) - - response = continuation(client_call_details, request) - if logging_enabled: # pragma: NO COVER - response_metadata = response.trailing_metadata() - # Convert gRPC metadata `` to list of tuples - metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None - result = response.result() - if isinstance(result, proto.Message): - response_payload = type(result).to_json(result) - elif isinstance(result, google.protobuf.message.Message): - response_payload = MessageToJson(result) - else: - response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" - grpc_response = { - "payload": response_payload, - "metadata": metadata, - "status": "OK", - } - _LOGGER.debug( - f"Received response for {client_call_details.method}.", - extra = { - "serviceName": "google.api.servicemanagement.v1.ServiceManager", - "rpcName": client_call_details.method, - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class ServiceManagerGrpcTransport(ServiceManagerTransport): - """gRPC backend transport for ServiceManager. - - `Google Service Management - API `__ - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends 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 = 'servicemanagement.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'servicemanagement.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if a ``channel`` instance is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if a ``channel`` instance is provided. - channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): - A ``Channel`` instance through which to make calls, or a Callable - that constructs and returns one. If set to None, ``self.create_channel`` - is used to create the channel. If a Callable is given, it will be called - with the same arguments as used in ``self.create_channel``. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if a ``channel`` instance is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if isinstance(channel, grpc.Channel): - # Ignore credentials if a channel was passed. - credentials = None - self._ignore_credentials = True - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - # initialize with the provided callable or the default channel - channel_init = channel or type(self).create_channel - self._grpc_channel = channel_init( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - self._interceptor = _LoggingClientInterceptor() - self._logged_channel = grpc.intercept_channel(self._grpc_channel, self._interceptor) - - # Wrap messages. This must be done after self._logged_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'servicemanagement.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsClient( - self._logged_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def list_services(self) -> Callable[ - [servicemanager.ListServicesRequest], - servicemanager.ListServicesResponse]: - r"""Return a callable for the list services method over gRPC. - - Lists managed services. - - Returns all public services. For authenticated users, - also returns all services the calling user has - "servicemanagement.services.get" permission for. - - Returns: - Callable[[~.ListServicesRequest], - ~.ListServicesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_services' not in self._stubs: - self._stubs['list_services'] = self._logged_channel.unary_unary( - '/google.api.servicemanagement.v1.ServiceManager/ListServices', - request_serializer=servicemanager.ListServicesRequest.serialize, - response_deserializer=servicemanager.ListServicesResponse.deserialize, - ) - return self._stubs['list_services'] - - @property - def get_service(self) -> Callable[ - [servicemanager.GetServiceRequest], - resources.ManagedService]: - r"""Return a callable for the get service method over gRPC. - - Gets a managed service. Authentication is required - unless the service is public. - - Returns: - Callable[[~.GetServiceRequest], - ~.ManagedService]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_service' not in self._stubs: - self._stubs['get_service'] = self._logged_channel.unary_unary( - '/google.api.servicemanagement.v1.ServiceManager/GetService', - request_serializer=servicemanager.GetServiceRequest.serialize, - response_deserializer=resources.ManagedService.deserialize, - ) - return self._stubs['get_service'] - - @property - def create_service(self) -> Callable[ - [servicemanager.CreateServiceRequest], - operations_pb2.Operation]: - r"""Return a callable for the create service method over gRPC. - - Creates a new managed service. - - A managed service is immutable, and is subject to - mandatory 30-day data retention. You cannot move a - service or recreate it within 30 days after deletion. - - One producer project can own no more than 500 services. - For security and reliability purposes, a production - service should be hosted in a dedicated producer - project. - - Operation - - Returns: - Callable[[~.CreateServiceRequest], - ~.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_service' not in self._stubs: - self._stubs['create_service'] = self._logged_channel.unary_unary( - '/google.api.servicemanagement.v1.ServiceManager/CreateService', - request_serializer=servicemanager.CreateServiceRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_service'] - - @property - def delete_service(self) -> Callable[ - [servicemanager.DeleteServiceRequest], - operations_pb2.Operation]: - r"""Return a callable for the delete service method over gRPC. - - Deletes a managed service. This method will change the service - to the ``Soft-Delete`` state for 30 days. Within this period, - service producers may call - [UndeleteService][google.api.servicemanagement.v1.ServiceManager.UndeleteService] - to restore the service. After 30 days, the service will be - permanently deleted. - - Operation - - Returns: - Callable[[~.DeleteServiceRequest], - ~.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_service' not in self._stubs: - self._stubs['delete_service'] = self._logged_channel.unary_unary( - '/google.api.servicemanagement.v1.ServiceManager/DeleteService', - request_serializer=servicemanager.DeleteServiceRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_service'] - - @property - def undelete_service(self) -> Callable[ - [servicemanager.UndeleteServiceRequest], - operations_pb2.Operation]: - r"""Return a callable for the undelete service method over gRPC. - - Revives a previously deleted managed service. The - method restores the service using the configuration at - the time the service was deleted. The target service - must exist and must have been deleted within the last 30 - days. - - Operation - - Returns: - Callable[[~.UndeleteServiceRequest], - ~.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 'undelete_service' not in self._stubs: - self._stubs['undelete_service'] = self._logged_channel.unary_unary( - '/google.api.servicemanagement.v1.ServiceManager/UndeleteService', - request_serializer=servicemanager.UndeleteServiceRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['undelete_service'] - - @property - def list_service_configs(self) -> Callable[ - [servicemanager.ListServiceConfigsRequest], - servicemanager.ListServiceConfigsResponse]: - r"""Return a callable for the list service configs method over gRPC. - - Lists the history of the service configuration for a - managed service, from the newest to the oldest. - - Returns: - Callable[[~.ListServiceConfigsRequest], - ~.ListServiceConfigsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_service_configs' not in self._stubs: - self._stubs['list_service_configs'] = self._logged_channel.unary_unary( - '/google.api.servicemanagement.v1.ServiceManager/ListServiceConfigs', - request_serializer=servicemanager.ListServiceConfigsRequest.serialize, - response_deserializer=servicemanager.ListServiceConfigsResponse.deserialize, - ) - return self._stubs['list_service_configs'] - - @property - def get_service_config(self) -> Callable[ - [servicemanager.GetServiceConfigRequest], - service_pb2.Service]: - r"""Return a callable for the get service config method over gRPC. - - Gets a service configuration (version) for a managed - service. - - Returns: - Callable[[~.GetServiceConfigRequest], - ~.Service]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_service_config' not in self._stubs: - self._stubs['get_service_config'] = self._logged_channel.unary_unary( - '/google.api.servicemanagement.v1.ServiceManager/GetServiceConfig', - request_serializer=servicemanager.GetServiceConfigRequest.serialize, - response_deserializer=service_pb2.Service.FromString, - ) - return self._stubs['get_service_config'] - - @property - def create_service_config(self) -> Callable[ - [servicemanager.CreateServiceConfigRequest], - service_pb2.Service]: - r"""Return a callable for the create service config method over gRPC. - - Creates a new service configuration (version) for a managed - service. This method only stores the service configuration. To - roll out the service configuration to backend systems please - call - [CreateServiceRollout][google.api.servicemanagement.v1.ServiceManager.CreateServiceRollout]. - - Only the 100 most recent service configurations and ones - referenced by existing rollouts are kept for each service. The - rest will be deleted eventually. - - Returns: - Callable[[~.CreateServiceConfigRequest], - ~.Service]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_service_config' not in self._stubs: - self._stubs['create_service_config'] = self._logged_channel.unary_unary( - '/google.api.servicemanagement.v1.ServiceManager/CreateServiceConfig', - request_serializer=servicemanager.CreateServiceConfigRequest.serialize, - response_deserializer=service_pb2.Service.FromString, - ) - return self._stubs['create_service_config'] - - @property - def submit_config_source(self) -> Callable[ - [servicemanager.SubmitConfigSourceRequest], - operations_pb2.Operation]: - r"""Return a callable for the submit config source method over gRPC. - - Creates a new service configuration (version) for a managed - service based on user-supplied configuration source files (for - example: OpenAPI Specification). This method stores the source - configurations as well as the generated service configuration. - To rollout the service configuration to other services, please - call - [CreateServiceRollout][google.api.servicemanagement.v1.ServiceManager.CreateServiceRollout]. - - Only the 100 most recent configuration sources and ones - referenced by existing service configurtions are kept for each - service. The rest will be deleted eventually. - - Operation - - Returns: - Callable[[~.SubmitConfigSourceRequest], - ~.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 'submit_config_source' not in self._stubs: - self._stubs['submit_config_source'] = self._logged_channel.unary_unary( - '/google.api.servicemanagement.v1.ServiceManager/SubmitConfigSource', - request_serializer=servicemanager.SubmitConfigSourceRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['submit_config_source'] - - @property - def list_service_rollouts(self) -> Callable[ - [servicemanager.ListServiceRolloutsRequest], - servicemanager.ListServiceRolloutsResponse]: - r"""Return a callable for the list service rollouts method over gRPC. - - Lists the history of the service configuration - rollouts for a managed service, from the newest to the - oldest. - - Returns: - Callable[[~.ListServiceRolloutsRequest], - ~.ListServiceRolloutsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_service_rollouts' not in self._stubs: - self._stubs['list_service_rollouts'] = self._logged_channel.unary_unary( - '/google.api.servicemanagement.v1.ServiceManager/ListServiceRollouts', - request_serializer=servicemanager.ListServiceRolloutsRequest.serialize, - response_deserializer=servicemanager.ListServiceRolloutsResponse.deserialize, - ) - return self._stubs['list_service_rollouts'] - - @property - def get_service_rollout(self) -> Callable[ - [servicemanager.GetServiceRolloutRequest], - resources.Rollout]: - r"""Return a callable for the get service rollout method over gRPC. - - Gets a service configuration - [rollout][google.api.servicemanagement.v1.Rollout]. - - Returns: - Callable[[~.GetServiceRolloutRequest], - ~.Rollout]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_service_rollout' not in self._stubs: - self._stubs['get_service_rollout'] = self._logged_channel.unary_unary( - '/google.api.servicemanagement.v1.ServiceManager/GetServiceRollout', - request_serializer=servicemanager.GetServiceRolloutRequest.serialize, - response_deserializer=resources.Rollout.deserialize, - ) - return self._stubs['get_service_rollout'] - - @property - def create_service_rollout(self) -> Callable[ - [servicemanager.CreateServiceRolloutRequest], - operations_pb2.Operation]: - r"""Return a callable for the create service rollout method over gRPC. - - Creates a new service configuration rollout. Based on - rollout, the Google Service Management will roll out the - service configurations to different backend services. - For example, the logging configuration will be pushed to - Google Cloud Logging. - - Please note that any previous pending and running - Rollouts and associated Operations will be automatically - cancelled so that the latest Rollout will not be blocked - by previous Rollouts. - - Only the 100 most recent (in any state) and the last 10 - successful (if not already part of the set of 100 most - recent) rollouts are kept for each service. The rest - will be deleted eventually. - - Operation - - Returns: - Callable[[~.CreateServiceRolloutRequest], - ~.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_service_rollout' not in self._stubs: - self._stubs['create_service_rollout'] = self._logged_channel.unary_unary( - '/google.api.servicemanagement.v1.ServiceManager/CreateServiceRollout', - request_serializer=servicemanager.CreateServiceRolloutRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_service_rollout'] - - @property - def generate_config_report(self) -> Callable[ - [servicemanager.GenerateConfigReportRequest], - servicemanager.GenerateConfigReportResponse]: - r"""Return a callable for the generate config report method over gRPC. - - Generates and returns a report (errors, warnings and changes - from existing configurations) associated with - GenerateConfigReportRequest.new_value - - If GenerateConfigReportRequest.old_value is specified, - GenerateConfigReportRequest will contain a single ChangeReport - based on the comparison between - GenerateConfigReportRequest.new_value and - GenerateConfigReportRequest.old_value. If - GenerateConfigReportRequest.old_value is not specified, this - method will compare GenerateConfigReportRequest.new_value with - the last pushed service configuration. - - Returns: - Callable[[~.GenerateConfigReportRequest], - ~.GenerateConfigReportResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'generate_config_report' not in self._stubs: - self._stubs['generate_config_report'] = self._logged_channel.unary_unary( - '/google.api.servicemanagement.v1.ServiceManager/GenerateConfigReport', - request_serializer=servicemanager.GenerateConfigReportRequest.serialize, - response_deserializer=servicemanager.GenerateConfigReportResponse.deserialize, - ) - return self._stubs['generate_config_report'] - - def close(self): - self._logged_channel.close() - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_operations" not in self._stubs: - self._stubs["list_operations"] = self._logged_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def set_iam_policy( - self, - ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: - r"""Return a callable for the set iam policy method over gRPC. - Sets the IAM access control policy on the specified - function. Replaces any existing policy. - Returns: - Callable[[~.SetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "set_iam_policy" not in self._stubs: - self._stubs["set_iam_policy"] = self._logged_channel.unary_unary( - "/google.iam.v1.IAMPolicy/SetIamPolicy", - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs["set_iam_policy"] - - @property - def get_iam_policy( - self, - ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: - r"""Return a callable for the get iam policy method over gRPC. - Gets the IAM access control policy for a function. - Returns an empty policy if the function exists and does - not have a policy set. - Returns: - Callable[[~.GetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_iam_policy" not in self._stubs: - self._stubs["get_iam_policy"] = self._logged_channel.unary_unary( - "/google.iam.v1.IAMPolicy/GetIamPolicy", - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs["get_iam_policy"] - - @property - def test_iam_permissions( - self, - ) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse - ]: - r"""Return a callable for the test iam permissions method over gRPC. - Tests the specified permissions against the IAM access control - policy for a function. If the function does not exist, this will - return an empty set of permissions, not a NOT_FOUND error. - Returns: - Callable[[~.TestIamPermissionsRequest], - ~.TestIamPermissionsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "test_iam_permissions" not in self._stubs: - self._stubs["test_iam_permissions"] = self._logged_channel.unary_unary( - "/google.iam.v1.IAMPolicy/TestIamPermissions", - request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, - ) - return self._stubs["test_iam_permissions"] - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'ServiceManagerGrpcTransport', -) diff --git a/owl-bot-staging/google-cloud-service-management/v1/google/cloud/servicemanagement_v1/services/service_manager/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-service-management/v1/google/cloud/servicemanagement_v1/services/service_manager/transports/grpc_asyncio.py deleted file mode 100644 index 26f7e363a6e4..000000000000 --- a/owl-bot-staging/google-cloud-service-management/v1/google/cloud/servicemanagement_v1/services/service_manager/transports/grpc_asyncio.py +++ /dev/null @@ -1,961 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import inspect -import json -import pickle -import logging as std_logging -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.api_core import exceptions as core_exceptions -from google.api_core import retry_async as retries -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.protobuf.json_format import MessageToJson -import google.protobuf.message - -import grpc # type: ignore -import proto # type: ignore -from grpc.experimental import aio # type: ignore - -from google.api import service_pb2 # type: ignore -from google.cloud.servicemanagement_v1.types import resources -from google.cloud.servicemanagement_v1.types import servicemanager -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 .base import ServiceManagerTransport, DEFAULT_CLIENT_INFO -from .grpc import ServiceManagerGrpcTransport - -try: - from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER -except ImportError: # pragma: NO COVER - CLIENT_LOGGING_SUPPORTED = False - -_LOGGER = std_logging.getLogger(__name__) - - -class _LoggingClientAIOInterceptor(grpc.aio.UnaryUnaryClientInterceptor): # pragma: NO COVER - async def intercept_unary_unary(self, continuation, client_call_details, request): - logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(std_logging.DEBUG) - if logging_enabled: # pragma: NO COVER - request_metadata = client_call_details.metadata - if isinstance(request, proto.Message): - request_payload = type(request).to_json(request) - elif isinstance(request, google.protobuf.message.Message): - request_payload = MessageToJson(request) - else: - request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" - - request_metadata = { - key: value.decode("utf-8") if isinstance(value, bytes) else value - for key, value in request_metadata - } - grpc_request = { - "payload": request_payload, - "requestMethod": "grpc", - "metadata": dict(request_metadata), - } - _LOGGER.debug( - f"Sending request for {client_call_details.method}", - extra = { - "serviceName": "google.api.servicemanagement.v1.ServiceManager", - "rpcName": str(client_call_details.method), - "request": grpc_request, - "metadata": grpc_request["metadata"], - }, - ) - response = await continuation(client_call_details, request) - if logging_enabled: # pragma: NO COVER - response_metadata = await response.trailing_metadata() - # Convert gRPC metadata `` to list of tuples - metadata = dict([(k, str(v)) for k, v in response_metadata]) if response_metadata else None - result = await response - if isinstance(result, proto.Message): - response_payload = type(result).to_json(result) - elif isinstance(result, google.protobuf.message.Message): - response_payload = MessageToJson(result) - else: - response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" - grpc_response = { - "payload": response_payload, - "metadata": metadata, - "status": "OK", - } - _LOGGER.debug( - f"Received response to rpc {client_call_details.method}.", - extra = { - "serviceName": "google.api.servicemanagement.v1.ServiceManager", - "rpcName": str(client_call_details.method), - "response": grpc_response, - "metadata": grpc_response["metadata"], - }, - ) - return response - - -class ServiceManagerGrpcAsyncIOTransport(ServiceManagerTransport): - """gRPC AsyncIO backend transport for ServiceManager. - - `Google Service Management - API `__ - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends 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 = 'servicemanagement.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'servicemanagement.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'servicemanagement.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if a ``channel`` instance is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]): - A ``Channel`` instance through which to make calls, or a Callable - that constructs and returns one. If set to None, ``self.create_channel`` - is used to create the channel. If a Callable is given, it will be called - with the same arguments as used in ``self.create_channel``. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if a ``channel`` instance is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if isinstance(channel, aio.Channel): - # Ignore credentials if a channel was passed. - credentials = None - self._ignore_credentials = True - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - # initialize with the provided callable or the default channel - channel_init = channel or type(self).create_channel - self._grpc_channel = channel_init( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - self._interceptor = _LoggingClientAIOInterceptor() - self._grpc_channel._unary_unary_interceptors.append(self._interceptor) - self._logged_channel = self._grpc_channel - self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters - # Wrap messages. This must be done after self._logged_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsAsyncClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsAsyncClient( - self._logged_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def list_services(self) -> Callable[ - [servicemanager.ListServicesRequest], - Awaitable[servicemanager.ListServicesResponse]]: - r"""Return a callable for the list services method over gRPC. - - Lists managed services. - - Returns all public services. For authenticated users, - also returns all services the calling user has - "servicemanagement.services.get" permission for. - - Returns: - Callable[[~.ListServicesRequest], - Awaitable[~.ListServicesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_services' not in self._stubs: - self._stubs['list_services'] = self._logged_channel.unary_unary( - '/google.api.servicemanagement.v1.ServiceManager/ListServices', - request_serializer=servicemanager.ListServicesRequest.serialize, - response_deserializer=servicemanager.ListServicesResponse.deserialize, - ) - return self._stubs['list_services'] - - @property - def get_service(self) -> Callable[ - [servicemanager.GetServiceRequest], - Awaitable[resources.ManagedService]]: - r"""Return a callable for the get service method over gRPC. - - Gets a managed service. Authentication is required - unless the service is public. - - Returns: - Callable[[~.GetServiceRequest], - Awaitable[~.ManagedService]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_service' not in self._stubs: - self._stubs['get_service'] = self._logged_channel.unary_unary( - '/google.api.servicemanagement.v1.ServiceManager/GetService', - request_serializer=servicemanager.GetServiceRequest.serialize, - response_deserializer=resources.ManagedService.deserialize, - ) - return self._stubs['get_service'] - - @property - def create_service(self) -> Callable[ - [servicemanager.CreateServiceRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the create service method over gRPC. - - Creates a new managed service. - - A managed service is immutable, and is subject to - mandatory 30-day data retention. You cannot move a - service or recreate it within 30 days after deletion. - - One producer project can own no more than 500 services. - For security and reliability purposes, a production - service should be hosted in a dedicated producer - project. - - Operation - - Returns: - Callable[[~.CreateServiceRequest], - 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_service' not in self._stubs: - self._stubs['create_service'] = self._logged_channel.unary_unary( - '/google.api.servicemanagement.v1.ServiceManager/CreateService', - request_serializer=servicemanager.CreateServiceRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_service'] - - @property - def delete_service(self) -> Callable[ - [servicemanager.DeleteServiceRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the delete service method over gRPC. - - Deletes a managed service. This method will change the service - to the ``Soft-Delete`` state for 30 days. Within this period, - service producers may call - [UndeleteService][google.api.servicemanagement.v1.ServiceManager.UndeleteService] - to restore the service. After 30 days, the service will be - permanently deleted. - - Operation - - Returns: - Callable[[~.DeleteServiceRequest], - 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_service' not in self._stubs: - self._stubs['delete_service'] = self._logged_channel.unary_unary( - '/google.api.servicemanagement.v1.ServiceManager/DeleteService', - request_serializer=servicemanager.DeleteServiceRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_service'] - - @property - def undelete_service(self) -> Callable[ - [servicemanager.UndeleteServiceRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the undelete service method over gRPC. - - Revives a previously deleted managed service. The - method restores the service using the configuration at - the time the service was deleted. The target service - must exist and must have been deleted within the last 30 - days. - - Operation - - Returns: - Callable[[~.UndeleteServiceRequest], - 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 'undelete_service' not in self._stubs: - self._stubs['undelete_service'] = self._logged_channel.unary_unary( - '/google.api.servicemanagement.v1.ServiceManager/UndeleteService', - request_serializer=servicemanager.UndeleteServiceRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['undelete_service'] - - @property - def list_service_configs(self) -> Callable[ - [servicemanager.ListServiceConfigsRequest], - Awaitable[servicemanager.ListServiceConfigsResponse]]: - r"""Return a callable for the list service configs method over gRPC. - - Lists the history of the service configuration for a - managed service, from the newest to the oldest. - - Returns: - Callable[[~.ListServiceConfigsRequest], - Awaitable[~.ListServiceConfigsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_service_configs' not in self._stubs: - self._stubs['list_service_configs'] = self._logged_channel.unary_unary( - '/google.api.servicemanagement.v1.ServiceManager/ListServiceConfigs', - request_serializer=servicemanager.ListServiceConfigsRequest.serialize, - response_deserializer=servicemanager.ListServiceConfigsResponse.deserialize, - ) - return self._stubs['list_service_configs'] - - @property - def get_service_config(self) -> Callable[ - [servicemanager.GetServiceConfigRequest], - Awaitable[service_pb2.Service]]: - r"""Return a callable for the get service config method over gRPC. - - Gets a service configuration (version) for a managed - service. - - Returns: - Callable[[~.GetServiceConfigRequest], - Awaitable[~.Service]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_service_config' not in self._stubs: - self._stubs['get_service_config'] = self._logged_channel.unary_unary( - '/google.api.servicemanagement.v1.ServiceManager/GetServiceConfig', - request_serializer=servicemanager.GetServiceConfigRequest.serialize, - response_deserializer=service_pb2.Service.FromString, - ) - return self._stubs['get_service_config'] - - @property - def create_service_config(self) -> Callable[ - [servicemanager.CreateServiceConfigRequest], - Awaitable[service_pb2.Service]]: - r"""Return a callable for the create service config method over gRPC. - - Creates a new service configuration (version) for a managed - service. This method only stores the service configuration. To - roll out the service configuration to backend systems please - call - [CreateServiceRollout][google.api.servicemanagement.v1.ServiceManager.CreateServiceRollout]. - - Only the 100 most recent service configurations and ones - referenced by existing rollouts are kept for each service. The - rest will be deleted eventually. - - Returns: - Callable[[~.CreateServiceConfigRequest], - Awaitable[~.Service]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_service_config' not in self._stubs: - self._stubs['create_service_config'] = self._logged_channel.unary_unary( - '/google.api.servicemanagement.v1.ServiceManager/CreateServiceConfig', - request_serializer=servicemanager.CreateServiceConfigRequest.serialize, - response_deserializer=service_pb2.Service.FromString, - ) - return self._stubs['create_service_config'] - - @property - def submit_config_source(self) -> Callable[ - [servicemanager.SubmitConfigSourceRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the submit config source method over gRPC. - - Creates a new service configuration (version) for a managed - service based on user-supplied configuration source files (for - example: OpenAPI Specification). This method stores the source - configurations as well as the generated service configuration. - To rollout the service configuration to other services, please - call - [CreateServiceRollout][google.api.servicemanagement.v1.ServiceManager.CreateServiceRollout]. - - Only the 100 most recent configuration sources and ones - referenced by existing service configurtions are kept for each - service. The rest will be deleted eventually. - - Operation - - Returns: - Callable[[~.SubmitConfigSourceRequest], - 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 'submit_config_source' not in self._stubs: - self._stubs['submit_config_source'] = self._logged_channel.unary_unary( - '/google.api.servicemanagement.v1.ServiceManager/SubmitConfigSource', - request_serializer=servicemanager.SubmitConfigSourceRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['submit_config_source'] - - @property - def list_service_rollouts(self) -> Callable[ - [servicemanager.ListServiceRolloutsRequest], - Awaitable[servicemanager.ListServiceRolloutsResponse]]: - r"""Return a callable for the list service rollouts method over gRPC. - - Lists the history of the service configuration - rollouts for a managed service, from the newest to the - oldest. - - Returns: - Callable[[~.ListServiceRolloutsRequest], - Awaitable[~.ListServiceRolloutsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_service_rollouts' not in self._stubs: - self._stubs['list_service_rollouts'] = self._logged_channel.unary_unary( - '/google.api.servicemanagement.v1.ServiceManager/ListServiceRollouts', - request_serializer=servicemanager.ListServiceRolloutsRequest.serialize, - response_deserializer=servicemanager.ListServiceRolloutsResponse.deserialize, - ) - return self._stubs['list_service_rollouts'] - - @property - def get_service_rollout(self) -> Callable[ - [servicemanager.GetServiceRolloutRequest], - Awaitable[resources.Rollout]]: - r"""Return a callable for the get service rollout method over gRPC. - - Gets a service configuration - [rollout][google.api.servicemanagement.v1.Rollout]. - - Returns: - Callable[[~.GetServiceRolloutRequest], - Awaitable[~.Rollout]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_service_rollout' not in self._stubs: - self._stubs['get_service_rollout'] = self._logged_channel.unary_unary( - '/google.api.servicemanagement.v1.ServiceManager/GetServiceRollout', - request_serializer=servicemanager.GetServiceRolloutRequest.serialize, - response_deserializer=resources.Rollout.deserialize, - ) - return self._stubs['get_service_rollout'] - - @property - def create_service_rollout(self) -> Callable[ - [servicemanager.CreateServiceRolloutRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the create service rollout method over gRPC. - - Creates a new service configuration rollout. Based on - rollout, the Google Service Management will roll out the - service configurations to different backend services. - For example, the logging configuration will be pushed to - Google Cloud Logging. - - Please note that any previous pending and running - Rollouts and associated Operations will be automatically - cancelled so that the latest Rollout will not be blocked - by previous Rollouts. - - Only the 100 most recent (in any state) and the last 10 - successful (if not already part of the set of 100 most - recent) rollouts are kept for each service. The rest - will be deleted eventually. - - Operation - - Returns: - Callable[[~.CreateServiceRolloutRequest], - 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_service_rollout' not in self._stubs: - self._stubs['create_service_rollout'] = self._logged_channel.unary_unary( - '/google.api.servicemanagement.v1.ServiceManager/CreateServiceRollout', - request_serializer=servicemanager.CreateServiceRolloutRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_service_rollout'] - - @property - def generate_config_report(self) -> Callable[ - [servicemanager.GenerateConfigReportRequest], - Awaitable[servicemanager.GenerateConfigReportResponse]]: - r"""Return a callable for the generate config report method over gRPC. - - Generates and returns a report (errors, warnings and changes - from existing configurations) associated with - GenerateConfigReportRequest.new_value - - If GenerateConfigReportRequest.old_value is specified, - GenerateConfigReportRequest will contain a single ChangeReport - based on the comparison between - GenerateConfigReportRequest.new_value and - GenerateConfigReportRequest.old_value. If - GenerateConfigReportRequest.old_value is not specified, this - method will compare GenerateConfigReportRequest.new_value with - the last pushed service configuration. - - Returns: - Callable[[~.GenerateConfigReportRequest], - Awaitable[~.GenerateConfigReportResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'generate_config_report' not in self._stubs: - self._stubs['generate_config_report'] = self._logged_channel.unary_unary( - '/google.api.servicemanagement.v1.ServiceManager/GenerateConfigReport', - request_serializer=servicemanager.GenerateConfigReportRequest.serialize, - response_deserializer=servicemanager.GenerateConfigReportResponse.deserialize, - ) - return self._stubs['generate_config_report'] - - def _prep_wrapped_messages(self, client_info): - """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" - self._wrapped_methods = { - self.list_services: self._wrap_method( - self.list_services, - default_timeout=None, - client_info=client_info, - ), - self.get_service: self._wrap_method( - self.get_service, - default_timeout=None, - client_info=client_info, - ), - self.create_service: self._wrap_method( - self.create_service, - default_timeout=None, - client_info=client_info, - ), - self.delete_service: self._wrap_method( - self.delete_service, - default_timeout=None, - client_info=client_info, - ), - self.undelete_service: self._wrap_method( - self.undelete_service, - default_timeout=None, - client_info=client_info, - ), - self.list_service_configs: self._wrap_method( - self.list_service_configs, - default_timeout=None, - client_info=client_info, - ), - self.get_service_config: self._wrap_method( - self.get_service_config, - default_timeout=None, - client_info=client_info, - ), - self.create_service_config: self._wrap_method( - self.create_service_config, - default_timeout=None, - client_info=client_info, - ), - self.submit_config_source: self._wrap_method( - self.submit_config_source, - default_timeout=None, - client_info=client_info, - ), - self.list_service_rollouts: self._wrap_method( - self.list_service_rollouts, - default_timeout=None, - client_info=client_info, - ), - self.get_service_rollout: self._wrap_method( - self.get_service_rollout, - default_timeout=None, - client_info=client_info, - ), - self.create_service_rollout: self._wrap_method( - self.create_service_rollout, - default_timeout=None, - client_info=client_info, - ), - self.generate_config_report: self._wrap_method( - self.generate_config_report, - default_timeout=None, - client_info=client_info, - ), - self.get_iam_policy: self._wrap_method( - self.get_iam_policy, - default_timeout=None, - client_info=client_info, - ), - self.set_iam_policy: self._wrap_method( - self.set_iam_policy, - default_timeout=None, - client_info=client_info, - ), - self.test_iam_permissions: self._wrap_method( - self.test_iam_permissions, - default_timeout=None, - client_info=client_info, - ), - self.list_operations: self._wrap_method( - self.list_operations, - default_timeout=None, - client_info=client_info, - ), - } - - def _wrap_method(self, func, *args, **kwargs): - if self._wrap_with_kind: # pragma: NO COVER - kwargs["kind"] = self.kind - return gapic_v1.method_async.wrap_method(func, *args, **kwargs) - - def close(self): - return self._logged_channel.close() - - @property - def kind(self) -> str: - return "grpc_asyncio" - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_operations" not in self._stubs: - self._stubs["list_operations"] = self._logged_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def set_iam_policy( - self, - ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: - r"""Return a callable for the set iam policy method over gRPC. - Sets the IAM access control policy on the specified - function. Replaces any existing policy. - Returns: - Callable[[~.SetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "set_iam_policy" not in self._stubs: - self._stubs["set_iam_policy"] = self._logged_channel.unary_unary( - "/google.iam.v1.IAMPolicy/SetIamPolicy", - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs["set_iam_policy"] - - @property - def get_iam_policy( - self, - ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: - r"""Return a callable for the get iam policy method over gRPC. - Gets the IAM access control policy for a function. - Returns an empty policy if the function exists and does - not have a policy set. - Returns: - Callable[[~.GetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_iam_policy" not in self._stubs: - self._stubs["get_iam_policy"] = self._logged_channel.unary_unary( - "/google.iam.v1.IAMPolicy/GetIamPolicy", - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs["get_iam_policy"] - - @property - def test_iam_permissions( - self, - ) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse - ]: - r"""Return a callable for the test iam permissions method over gRPC. - Tests the specified permissions against the IAM access control - policy for a function. If the function does not exist, this will - return an empty set of permissions, not a NOT_FOUND error. - Returns: - Callable[[~.TestIamPermissionsRequest], - ~.TestIamPermissionsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "test_iam_permissions" not in self._stubs: - self._stubs["test_iam_permissions"] = self._logged_channel.unary_unary( - "/google.iam.v1.IAMPolicy/TestIamPermissions", - request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, - ) - return self._stubs["test_iam_permissions"] - - -__all__ = ( - 'ServiceManagerGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-cloud-service-management/v1/google/cloud/servicemanagement_v1/services/service_manager/transports/rest.py b/owl-bot-staging/google-cloud-service-management/v1/google/cloud/servicemanagement_v1/services/service_manager/transports/rest.py deleted file mode 100644 index 4ca39e5988b6..000000000000 --- a/owl-bot-staging/google-cloud-service-management/v1/google/cloud/servicemanagement_v1/services/service_manager/transports/rest.py +++ /dev/null @@ -1,2850 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import logging -import json # type: ignore - -from google.auth.transport.requests import AuthorizedSession # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import gapic_v1 - -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 requests import __version__ as requests_version -import dataclasses -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - - -from google.api import service_pb2 # type: ignore -from google.cloud.servicemanagement_v1.types import resources -from google.cloud.servicemanagement_v1.types import servicemanager -from google.longrunning import operations_pb2 # type: ignore - - -from .rest_base import _BaseServiceManagerRestTransport -from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - -try: - from google.api_core import client_logging # type: ignore - CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER -except ImportError: # pragma: NO COVER - CLIENT_LOGGING_SUPPORTED = False - -_LOGGER = logging.getLogger(__name__) - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=f"requests@{requests_version}", -) - - -class ServiceManagerRestInterceptor: - """Interceptor for ServiceManager. - - 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 ServiceManagerRestTransport. - - .. code-block:: python - class MyCustomServiceManagerInterceptor(ServiceManagerRestInterceptor): - def pre_create_service(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_service(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_service_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_service_config(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_service_rollout(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_service_rollout(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_service(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_delete_service(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_generate_config_report(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_generate_config_report(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_service(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_service(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_service_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_service_config(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_service_rollout(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_service_rollout(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_service_configs(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_service_configs(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_service_rollouts(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_service_rollouts(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_services(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_services(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_submit_config_source(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_submit_config_source(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_undelete_service(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_undelete_service(self, response): - logging.log(f"Received response: {response}") - return response - - transport = ServiceManagerRestTransport(interceptor=MyCustomServiceManagerInterceptor()) - client = ServiceManagerClient(transport=transport) - - - """ - def pre_create_service(self, request: servicemanager.CreateServiceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[servicemanager.CreateServiceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for create_service - - Override in a subclass to manipulate the request or metadata - before they are sent to the ServiceManager server. - """ - return request, metadata - - def post_create_service(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for create_service - - Override in a subclass to manipulate the response - after it is returned by the ServiceManager server but before - it is returned to user code. - """ - return response - - def pre_create_service_config(self, request: servicemanager.CreateServiceConfigRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[servicemanager.CreateServiceConfigRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for create_service_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the ServiceManager server. - """ - return request, metadata - - def post_create_service_config(self, response: service_pb2.Service) -> service_pb2.Service: - """Post-rpc interceptor for create_service_config - - Override in a subclass to manipulate the response - after it is returned by the ServiceManager server but before - it is returned to user code. - """ - return response - - def pre_create_service_rollout(self, request: servicemanager.CreateServiceRolloutRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[servicemanager.CreateServiceRolloutRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for create_service_rollout - - Override in a subclass to manipulate the request or metadata - before they are sent to the ServiceManager server. - """ - return request, metadata - - def post_create_service_rollout(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for create_service_rollout - - Override in a subclass to manipulate the response - after it is returned by the ServiceManager server but before - it is returned to user code. - """ - return response - - def pre_delete_service(self, request: servicemanager.DeleteServiceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[servicemanager.DeleteServiceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for delete_service - - Override in a subclass to manipulate the request or metadata - before they are sent to the ServiceManager server. - """ - return request, metadata - - def post_delete_service(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for delete_service - - Override in a subclass to manipulate the response - after it is returned by the ServiceManager server but before - it is returned to user code. - """ - return response - - def pre_generate_config_report(self, request: servicemanager.GenerateConfigReportRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[servicemanager.GenerateConfigReportRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for generate_config_report - - Override in a subclass to manipulate the request or metadata - before they are sent to the ServiceManager server. - """ - return request, metadata - - def post_generate_config_report(self, response: servicemanager.GenerateConfigReportResponse) -> servicemanager.GenerateConfigReportResponse: - """Post-rpc interceptor for generate_config_report - - Override in a subclass to manipulate the response - after it is returned by the ServiceManager server but before - it is returned to user code. - """ - return response - - def pre_get_service(self, request: servicemanager.GetServiceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[servicemanager.GetServiceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for get_service - - Override in a subclass to manipulate the request or metadata - before they are sent to the ServiceManager server. - """ - return request, metadata - - def post_get_service(self, response: resources.ManagedService) -> resources.ManagedService: - """Post-rpc interceptor for get_service - - Override in a subclass to manipulate the response - after it is returned by the ServiceManager server but before - it is returned to user code. - """ - return response - - def pre_get_service_config(self, request: servicemanager.GetServiceConfigRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[servicemanager.GetServiceConfigRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for get_service_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the ServiceManager server. - """ - return request, metadata - - def post_get_service_config(self, response: service_pb2.Service) -> service_pb2.Service: - """Post-rpc interceptor for get_service_config - - Override in a subclass to manipulate the response - after it is returned by the ServiceManager server but before - it is returned to user code. - """ - return response - - def pre_get_service_rollout(self, request: servicemanager.GetServiceRolloutRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[servicemanager.GetServiceRolloutRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for get_service_rollout - - Override in a subclass to manipulate the request or metadata - before they are sent to the ServiceManager server. - """ - return request, metadata - - def post_get_service_rollout(self, response: resources.Rollout) -> resources.Rollout: - """Post-rpc interceptor for get_service_rollout - - Override in a subclass to manipulate the response - after it is returned by the ServiceManager server but before - it is returned to user code. - """ - return response - - def pre_list_service_configs(self, request: servicemanager.ListServiceConfigsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[servicemanager.ListServiceConfigsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for list_service_configs - - Override in a subclass to manipulate the request or metadata - before they are sent to the ServiceManager server. - """ - return request, metadata - - def post_list_service_configs(self, response: servicemanager.ListServiceConfigsResponse) -> servicemanager.ListServiceConfigsResponse: - """Post-rpc interceptor for list_service_configs - - Override in a subclass to manipulate the response - after it is returned by the ServiceManager server but before - it is returned to user code. - """ - return response - - def pre_list_service_rollouts(self, request: servicemanager.ListServiceRolloutsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[servicemanager.ListServiceRolloutsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for list_service_rollouts - - Override in a subclass to manipulate the request or metadata - before they are sent to the ServiceManager server. - """ - return request, metadata - - def post_list_service_rollouts(self, response: servicemanager.ListServiceRolloutsResponse) -> servicemanager.ListServiceRolloutsResponse: - """Post-rpc interceptor for list_service_rollouts - - Override in a subclass to manipulate the response - after it is returned by the ServiceManager server but before - it is returned to user code. - """ - return response - - def pre_list_services(self, request: servicemanager.ListServicesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[servicemanager.ListServicesRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for list_services - - Override in a subclass to manipulate the request or metadata - before they are sent to the ServiceManager server. - """ - return request, metadata - - def post_list_services(self, response: servicemanager.ListServicesResponse) -> servicemanager.ListServicesResponse: - """Post-rpc interceptor for list_services - - Override in a subclass to manipulate the response - after it is returned by the ServiceManager server but before - it is returned to user code. - """ - return response - - def pre_submit_config_source(self, request: servicemanager.SubmitConfigSourceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[servicemanager.SubmitConfigSourceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for submit_config_source - - Override in a subclass to manipulate the request or metadata - before they are sent to the ServiceManager server. - """ - return request, metadata - - def post_submit_config_source(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for submit_config_source - - Override in a subclass to manipulate the response - after it is returned by the ServiceManager server but before - it is returned to user code. - """ - return response - - def pre_undelete_service(self, request: servicemanager.UndeleteServiceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]]) -> Tuple[servicemanager.UndeleteServiceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for undelete_service - - Override in a subclass to manipulate the request or metadata - before they are sent to the ServiceManager server. - """ - return request, metadata - - def post_undelete_service(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for undelete_service - - Override in a subclass to manipulate the response - after it is returned by the ServiceManager server but before - it is returned to user code. - """ - return response - - def pre_get_iam_policy( - self, request: iam_policy_pb2.GetIamPolicyRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for get_iam_policy - - Override in a subclass to manipulate the request or metadata - before they are sent to the ServiceManager 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 ServiceManager server but before - it is returned to user code. - """ - return response - - def pre_set_iam_policy( - self, request: iam_policy_pb2.SetIamPolicyRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for set_iam_policy - - Override in a subclass to manipulate the request or metadata - before they are sent to the ServiceManager 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 ServiceManager server but before - it is returned to user code. - """ - return response - - def pre_test_iam_permissions( - self, request: iam_policy_pb2.TestIamPermissionsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[iam_policy_pb2.TestIamPermissionsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for test_iam_permissions - - Override in a subclass to manipulate the request or metadata - before they are sent to the ServiceManager 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 ServiceManager server but before - it is returned to user code. - """ - return response - - def pre_list_operations( - self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]] - ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for list_operations - - Override in a subclass to manipulate the request or metadata - before they are sent to the ServiceManager 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 ServiceManager server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class ServiceManagerRestStub: - _session: AuthorizedSession - _host: str - _interceptor: ServiceManagerRestInterceptor - - -class ServiceManagerRestTransport(_BaseServiceManagerRestTransport): - """REST backend synchronous transport for ServiceManager. - - `Google Service Management - API `__ - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends JSON representations of protocol buffers over HTTP/1.1 - """ - - def __init__(self, *, - host: str = 'servicemanagement.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[ServiceManagerRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'servicemanagement.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - url_scheme=url_scheme, - api_audience=api_audience - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) - self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or ServiceManagerRestInterceptor() - 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.ListOperations': [ - { - 'method': 'get', - 'uri': '/v1/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 _CreateService(_BaseServiceManagerRestTransport._BaseCreateService, ServiceManagerRestStub): - def __hash__(self): - return hash("ServiceManagerRestTransport.CreateService") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: servicemanager.CreateServiceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: - r"""Call the create service method over HTTP. - - Args: - request (~.servicemanager.CreateServiceRequest): - The request object. Request message for CreateService - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseServiceManagerRestTransport._BaseCreateService._get_http_options() - - request, metadata = self._interceptor.pre_create_service(request, metadata) - transcoded_request = _BaseServiceManagerRestTransport._BaseCreateService._get_transcoded_request(http_options, request) - - body = _BaseServiceManagerRestTransport._BaseCreateService._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseServiceManagerRestTransport._BaseCreateService._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.api.servicemanagement_v1.ServiceManagerClient.CreateService", - extra = { - "serviceName": "google.api.servicemanagement.v1.ServiceManager", - "rpcName": "CreateService", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = ServiceManagerRestTransport._CreateService._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_create_service(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = json_format.MessageToJson(resp) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.api.servicemanagement_v1.ServiceManagerClient.create_service", - extra = { - "serviceName": "google.api.servicemanagement.v1.ServiceManager", - "rpcName": "CreateService", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _CreateServiceConfig(_BaseServiceManagerRestTransport._BaseCreateServiceConfig, ServiceManagerRestStub): - def __hash__(self): - return hash("ServiceManagerRestTransport.CreateServiceConfig") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: servicemanager.CreateServiceConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> service_pb2.Service: - r"""Call the create service config method over HTTP. - - Args: - request (~.servicemanager.CreateServiceConfigRequest): - The request object. Request message for - CreateServiceConfig method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.service_pb2.Service: - ``Service`` is the root object of Google API service - configuration (service config). It describes the basic - information about a logical service, such as the service - name and the user-facing title, and delegates other - aspects to sub-sections. Each sub-section is either a - proto message or a repeated proto message that - configures a specific aspect, such as auth. For more - information, see each proto message definition. - - Example: - - :: - - type: google.api.Service - name: calendar.googleapis.com - title: Google Calendar API - apis: - - name: google.calendar.v3.Calendar - - visibility: - rules: - - selector: "google.calendar.v3.*" - restriction: PREVIEW - backend: - rules: - - selector: "google.calendar.v3.*" - address: calendar.example.com - - authentication: - providers: - - id: google_calendar_auth - jwks_uri: https://www.googleapis.com/oauth2/v1/certs - issuer: https://securetoken.google.com - rules: - - selector: "*" - requirements: - provider_id: google_calendar_auth - - """ - - http_options = _BaseServiceManagerRestTransport._BaseCreateServiceConfig._get_http_options() - - request, metadata = self._interceptor.pre_create_service_config(request, metadata) - transcoded_request = _BaseServiceManagerRestTransport._BaseCreateServiceConfig._get_transcoded_request(http_options, request) - - body = _BaseServiceManagerRestTransport._BaseCreateServiceConfig._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseServiceManagerRestTransport._BaseCreateServiceConfig._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.api.servicemanagement_v1.ServiceManagerClient.CreateServiceConfig", - extra = { - "serviceName": "google.api.servicemanagement.v1.ServiceManager", - "rpcName": "CreateServiceConfig", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = ServiceManagerRestTransport._CreateServiceConfig._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = service_pb2.Service() - pb_resp = resp - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_create_service_config(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = json_format.MessageToJson(resp) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.api.servicemanagement_v1.ServiceManagerClient.create_service_config", - extra = { - "serviceName": "google.api.servicemanagement.v1.ServiceManager", - "rpcName": "CreateServiceConfig", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _CreateServiceRollout(_BaseServiceManagerRestTransport._BaseCreateServiceRollout, ServiceManagerRestStub): - def __hash__(self): - return hash("ServiceManagerRestTransport.CreateServiceRollout") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: servicemanager.CreateServiceRolloutRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: - r"""Call the create service rollout method over HTTP. - - Args: - request (~.servicemanager.CreateServiceRolloutRequest): - The request object. Request message for - 'CreateServiceRollout' - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseServiceManagerRestTransport._BaseCreateServiceRollout._get_http_options() - - request, metadata = self._interceptor.pre_create_service_rollout(request, metadata) - transcoded_request = _BaseServiceManagerRestTransport._BaseCreateServiceRollout._get_transcoded_request(http_options, request) - - body = _BaseServiceManagerRestTransport._BaseCreateServiceRollout._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseServiceManagerRestTransport._BaseCreateServiceRollout._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.api.servicemanagement_v1.ServiceManagerClient.CreateServiceRollout", - extra = { - "serviceName": "google.api.servicemanagement.v1.ServiceManager", - "rpcName": "CreateServiceRollout", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = ServiceManagerRestTransport._CreateServiceRollout._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_create_service_rollout(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = json_format.MessageToJson(resp) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.api.servicemanagement_v1.ServiceManagerClient.create_service_rollout", - extra = { - "serviceName": "google.api.servicemanagement.v1.ServiceManager", - "rpcName": "CreateServiceRollout", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _DeleteService(_BaseServiceManagerRestTransport._BaseDeleteService, ServiceManagerRestStub): - def __hash__(self): - return hash("ServiceManagerRestTransport.DeleteService") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: servicemanager.DeleteServiceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: - r"""Call the delete service method over HTTP. - - Args: - request (~.servicemanager.DeleteServiceRequest): - The request object. Request message for DeleteService - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseServiceManagerRestTransport._BaseDeleteService._get_http_options() - - request, metadata = self._interceptor.pre_delete_service(request, metadata) - transcoded_request = _BaseServiceManagerRestTransport._BaseDeleteService._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseServiceManagerRestTransport._BaseDeleteService._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.api.servicemanagement_v1.ServiceManagerClient.DeleteService", - extra = { - "serviceName": "google.api.servicemanagement.v1.ServiceManager", - "rpcName": "DeleteService", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = ServiceManagerRestTransport._DeleteService._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_delete_service(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = json_format.MessageToJson(resp) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.api.servicemanagement_v1.ServiceManagerClient.delete_service", - extra = { - "serviceName": "google.api.servicemanagement.v1.ServiceManager", - "rpcName": "DeleteService", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _GenerateConfigReport(_BaseServiceManagerRestTransport._BaseGenerateConfigReport, ServiceManagerRestStub): - def __hash__(self): - return hash("ServiceManagerRestTransport.GenerateConfigReport") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: servicemanager.GenerateConfigReportRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> servicemanager.GenerateConfigReportResponse: - r"""Call the generate config report method over HTTP. - - Args: - request (~.servicemanager.GenerateConfigReportRequest): - The request object. Request message for - GenerateConfigReport method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.servicemanager.GenerateConfigReportResponse: - Response message for - GenerateConfigReport method. - - """ - - http_options = _BaseServiceManagerRestTransport._BaseGenerateConfigReport._get_http_options() - - request, metadata = self._interceptor.pre_generate_config_report(request, metadata) - transcoded_request = _BaseServiceManagerRestTransport._BaseGenerateConfigReport._get_transcoded_request(http_options, request) - - body = _BaseServiceManagerRestTransport._BaseGenerateConfigReport._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseServiceManagerRestTransport._BaseGenerateConfigReport._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = type(request).to_json(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.api.servicemanagement_v1.ServiceManagerClient.GenerateConfigReport", - extra = { - "serviceName": "google.api.servicemanagement.v1.ServiceManager", - "rpcName": "GenerateConfigReport", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = ServiceManagerRestTransport._GenerateConfigReport._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = servicemanager.GenerateConfigReportResponse() - pb_resp = servicemanager.GenerateConfigReportResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_generate_config_report(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = servicemanager.GenerateConfigReportResponse.to_json(response) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.api.servicemanagement_v1.ServiceManagerClient.generate_config_report", - extra = { - "serviceName": "google.api.servicemanagement.v1.ServiceManager", - "rpcName": "GenerateConfigReport", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _GetService(_BaseServiceManagerRestTransport._BaseGetService, ServiceManagerRestStub): - def __hash__(self): - return hash("ServiceManagerRestTransport.GetService") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: servicemanager.GetServiceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> resources.ManagedService: - r"""Call the get service method over HTTP. - - Args: - request (~.servicemanager.GetServiceRequest): - The request object. Request message for ``GetService`` method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.resources.ManagedService: - The full representation of a Service - that is managed by Google Service - Management. - - """ - - http_options = _BaseServiceManagerRestTransport._BaseGetService._get_http_options() - - request, metadata = self._interceptor.pre_get_service(request, metadata) - transcoded_request = _BaseServiceManagerRestTransport._BaseGetService._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseServiceManagerRestTransport._BaseGetService._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = type(request).to_json(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.api.servicemanagement_v1.ServiceManagerClient.GetService", - extra = { - "serviceName": "google.api.servicemanagement.v1.ServiceManager", - "rpcName": "GetService", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = ServiceManagerRestTransport._GetService._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = resources.ManagedService() - pb_resp = resources.ManagedService.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_get_service(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = resources.ManagedService.to_json(response) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.api.servicemanagement_v1.ServiceManagerClient.get_service", - extra = { - "serviceName": "google.api.servicemanagement.v1.ServiceManager", - "rpcName": "GetService", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _GetServiceConfig(_BaseServiceManagerRestTransport._BaseGetServiceConfig, ServiceManagerRestStub): - def __hash__(self): - return hash("ServiceManagerRestTransport.GetServiceConfig") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: servicemanager.GetServiceConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> service_pb2.Service: - r"""Call the get service config method over HTTP. - - Args: - request (~.servicemanager.GetServiceConfigRequest): - The request object. Request message for GetServiceConfig - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.service_pb2.Service: - ``Service`` is the root object of Google API service - configuration (service config). It describes the basic - information about a logical service, such as the service - name and the user-facing title, and delegates other - aspects to sub-sections. Each sub-section is either a - proto message or a repeated proto message that - configures a specific aspect, such as auth. For more - information, see each proto message definition. - - Example: - - :: - - type: google.api.Service - name: calendar.googleapis.com - title: Google Calendar API - apis: - - name: google.calendar.v3.Calendar - - visibility: - rules: - - selector: "google.calendar.v3.*" - restriction: PREVIEW - backend: - rules: - - selector: "google.calendar.v3.*" - address: calendar.example.com - - authentication: - providers: - - id: google_calendar_auth - jwks_uri: https://www.googleapis.com/oauth2/v1/certs - issuer: https://securetoken.google.com - rules: - - selector: "*" - requirements: - provider_id: google_calendar_auth - - """ - - http_options = _BaseServiceManagerRestTransport._BaseGetServiceConfig._get_http_options() - - request, metadata = self._interceptor.pre_get_service_config(request, metadata) - transcoded_request = _BaseServiceManagerRestTransport._BaseGetServiceConfig._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseServiceManagerRestTransport._BaseGetServiceConfig._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.api.servicemanagement_v1.ServiceManagerClient.GetServiceConfig", - extra = { - "serviceName": "google.api.servicemanagement.v1.ServiceManager", - "rpcName": "GetServiceConfig", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = ServiceManagerRestTransport._GetServiceConfig._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = service_pb2.Service() - pb_resp = resp - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_get_service_config(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = json_format.MessageToJson(resp) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.api.servicemanagement_v1.ServiceManagerClient.get_service_config", - extra = { - "serviceName": "google.api.servicemanagement.v1.ServiceManager", - "rpcName": "GetServiceConfig", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _GetServiceRollout(_BaseServiceManagerRestTransport._BaseGetServiceRollout, ServiceManagerRestStub): - def __hash__(self): - return hash("ServiceManagerRestTransport.GetServiceRollout") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: servicemanager.GetServiceRolloutRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> resources.Rollout: - r"""Call the get service rollout method over HTTP. - - Args: - request (~.servicemanager.GetServiceRolloutRequest): - The request object. Request message for GetServiceRollout - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.resources.Rollout: - A rollout resource that defines how - service configuration versions are - pushed to control plane systems. - Typically, you create a new version of - the service config, and then create a - Rollout to push the service config. - - """ - - http_options = _BaseServiceManagerRestTransport._BaseGetServiceRollout._get_http_options() - - request, metadata = self._interceptor.pre_get_service_rollout(request, metadata) - transcoded_request = _BaseServiceManagerRestTransport._BaseGetServiceRollout._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseServiceManagerRestTransport._BaseGetServiceRollout._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = type(request).to_json(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.api.servicemanagement_v1.ServiceManagerClient.GetServiceRollout", - extra = { - "serviceName": "google.api.servicemanagement.v1.ServiceManager", - "rpcName": "GetServiceRollout", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = ServiceManagerRestTransport._GetServiceRollout._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = resources.Rollout() - pb_resp = resources.Rollout.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_get_service_rollout(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = resources.Rollout.to_json(response) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.api.servicemanagement_v1.ServiceManagerClient.get_service_rollout", - extra = { - "serviceName": "google.api.servicemanagement.v1.ServiceManager", - "rpcName": "GetServiceRollout", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _ListServiceConfigs(_BaseServiceManagerRestTransport._BaseListServiceConfigs, ServiceManagerRestStub): - def __hash__(self): - return hash("ServiceManagerRestTransport.ListServiceConfigs") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: servicemanager.ListServiceConfigsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> servicemanager.ListServiceConfigsResponse: - r"""Call the list service configs method over HTTP. - - Args: - request (~.servicemanager.ListServiceConfigsRequest): - The request object. Request message for - ListServiceConfigs method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.servicemanager.ListServiceConfigsResponse: - Response message for - ListServiceConfigs method. - - """ - - http_options = _BaseServiceManagerRestTransport._BaseListServiceConfigs._get_http_options() - - request, metadata = self._interceptor.pre_list_service_configs(request, metadata) - transcoded_request = _BaseServiceManagerRestTransport._BaseListServiceConfigs._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseServiceManagerRestTransport._BaseListServiceConfigs._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = type(request).to_json(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.api.servicemanagement_v1.ServiceManagerClient.ListServiceConfigs", - extra = { - "serviceName": "google.api.servicemanagement.v1.ServiceManager", - "rpcName": "ListServiceConfigs", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = ServiceManagerRestTransport._ListServiceConfigs._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = servicemanager.ListServiceConfigsResponse() - pb_resp = servicemanager.ListServiceConfigsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_list_service_configs(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = servicemanager.ListServiceConfigsResponse.to_json(response) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.api.servicemanagement_v1.ServiceManagerClient.list_service_configs", - extra = { - "serviceName": "google.api.servicemanagement.v1.ServiceManager", - "rpcName": "ListServiceConfigs", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _ListServiceRollouts(_BaseServiceManagerRestTransport._BaseListServiceRollouts, ServiceManagerRestStub): - def __hash__(self): - return hash("ServiceManagerRestTransport.ListServiceRollouts") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: servicemanager.ListServiceRolloutsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> servicemanager.ListServiceRolloutsResponse: - r"""Call the list service rollouts method over HTTP. - - Args: - request (~.servicemanager.ListServiceRolloutsRequest): - The request object. Request message for - 'ListServiceRollouts' - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.servicemanager.ListServiceRolloutsResponse: - Response message for - ListServiceRollouts method. - - """ - - http_options = _BaseServiceManagerRestTransport._BaseListServiceRollouts._get_http_options() - - request, metadata = self._interceptor.pre_list_service_rollouts(request, metadata) - transcoded_request = _BaseServiceManagerRestTransport._BaseListServiceRollouts._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseServiceManagerRestTransport._BaseListServiceRollouts._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = type(request).to_json(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.api.servicemanagement_v1.ServiceManagerClient.ListServiceRollouts", - extra = { - "serviceName": "google.api.servicemanagement.v1.ServiceManager", - "rpcName": "ListServiceRollouts", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = ServiceManagerRestTransport._ListServiceRollouts._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = servicemanager.ListServiceRolloutsResponse() - pb_resp = servicemanager.ListServiceRolloutsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_list_service_rollouts(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = servicemanager.ListServiceRolloutsResponse.to_json(response) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.api.servicemanagement_v1.ServiceManagerClient.list_service_rollouts", - extra = { - "serviceName": "google.api.servicemanagement.v1.ServiceManager", - "rpcName": "ListServiceRollouts", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _ListServices(_BaseServiceManagerRestTransport._BaseListServices, ServiceManagerRestStub): - def __hash__(self): - return hash("ServiceManagerRestTransport.ListServices") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: servicemanager.ListServicesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> servicemanager.ListServicesResponse: - r"""Call the list services method over HTTP. - - Args: - request (~.servicemanager.ListServicesRequest): - The request object. Request message for ``ListServices`` method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.servicemanager.ListServicesResponse: - Response message for ``ListServices`` method. - """ - - http_options = _BaseServiceManagerRestTransport._BaseListServices._get_http_options() - - request, metadata = self._interceptor.pre_list_services(request, metadata) - transcoded_request = _BaseServiceManagerRestTransport._BaseListServices._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseServiceManagerRestTransport._BaseListServices._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = type(request).to_json(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.api.servicemanagement_v1.ServiceManagerClient.ListServices", - extra = { - "serviceName": "google.api.servicemanagement.v1.ServiceManager", - "rpcName": "ListServices", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = ServiceManagerRestTransport._ListServices._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = servicemanager.ListServicesResponse() - pb_resp = servicemanager.ListServicesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_list_services(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = servicemanager.ListServicesResponse.to_json(response) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.api.servicemanagement_v1.ServiceManagerClient.list_services", - extra = { - "serviceName": "google.api.servicemanagement.v1.ServiceManager", - "rpcName": "ListServices", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _SubmitConfigSource(_BaseServiceManagerRestTransport._BaseSubmitConfigSource, ServiceManagerRestStub): - def __hash__(self): - return hash("ServiceManagerRestTransport.SubmitConfigSource") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: servicemanager.SubmitConfigSourceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: - r"""Call the submit config source method over HTTP. - - Args: - request (~.servicemanager.SubmitConfigSourceRequest): - The request object. Request message for - SubmitConfigSource method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseServiceManagerRestTransport._BaseSubmitConfigSource._get_http_options() - - request, metadata = self._interceptor.pre_submit_config_source(request, metadata) - transcoded_request = _BaseServiceManagerRestTransport._BaseSubmitConfigSource._get_transcoded_request(http_options, request) - - body = _BaseServiceManagerRestTransport._BaseSubmitConfigSource._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseServiceManagerRestTransport._BaseSubmitConfigSource._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.api.servicemanagement_v1.ServiceManagerClient.SubmitConfigSource", - extra = { - "serviceName": "google.api.servicemanagement.v1.ServiceManager", - "rpcName": "SubmitConfigSource", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = ServiceManagerRestTransport._SubmitConfigSource._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_submit_config_source(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = json_format.MessageToJson(resp) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.api.servicemanagement_v1.ServiceManagerClient.submit_config_source", - extra = { - "serviceName": "google.api.servicemanagement.v1.ServiceManager", - "rpcName": "SubmitConfigSource", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - class _UndeleteService(_BaseServiceManagerRestTransport._BaseUndeleteService, ServiceManagerRestStub): - def __hash__(self): - return hash("ServiceManagerRestTransport.UndeleteService") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: servicemanager.UndeleteServiceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.Operation: - r"""Call the undelete service method over HTTP. - - Args: - request (~.servicemanager.UndeleteServiceRequest): - The request object. Request message for UndeleteService - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseServiceManagerRestTransport._BaseUndeleteService._get_http_options() - - request, metadata = self._interceptor.pre_undelete_service(request, metadata) - transcoded_request = _BaseServiceManagerRestTransport._BaseUndeleteService._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseServiceManagerRestTransport._BaseUndeleteService._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.api.servicemanagement_v1.ServiceManagerClient.UndeleteService", - extra = { - "serviceName": "google.api.servicemanagement.v1.ServiceManager", - "rpcName": "UndeleteService", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = ServiceManagerRestTransport._UndeleteService._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - - resp = self._interceptor.post_undelete_service(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = json_format.MessageToJson(resp) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.api.servicemanagement_v1.ServiceManagerClient.undelete_service", - extra = { - "serviceName": "google.api.servicemanagement.v1.ServiceManager", - "rpcName": "UndeleteService", - "metadata": http_response["headers"], - "httpResponse": http_response, - }, - ) - return resp - - @property - def create_service(self) -> Callable[ - [servicemanager.CreateServiceRequest], - 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._CreateService(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_service_config(self) -> Callable[ - [servicemanager.CreateServiceConfigRequest], - service_pb2.Service]: - # 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._CreateServiceConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_service_rollout(self) -> Callable[ - [servicemanager.CreateServiceRolloutRequest], - 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._CreateServiceRollout(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_service(self) -> Callable[ - [servicemanager.DeleteServiceRequest], - 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._DeleteService(self._session, self._host, self._interceptor) # type: ignore - - @property - def generate_config_report(self) -> Callable[ - [servicemanager.GenerateConfigReportRequest], - servicemanager.GenerateConfigReportResponse]: - # 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._GenerateConfigReport(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_service(self) -> Callable[ - [servicemanager.GetServiceRequest], - resources.ManagedService]: - # 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._GetService(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_service_config(self) -> Callable[ - [servicemanager.GetServiceConfigRequest], - service_pb2.Service]: - # 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._GetServiceConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_service_rollout(self) -> Callable[ - [servicemanager.GetServiceRolloutRequest], - resources.Rollout]: - # 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._GetServiceRollout(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_service_configs(self) -> Callable[ - [servicemanager.ListServiceConfigsRequest], - servicemanager.ListServiceConfigsResponse]: - # 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._ListServiceConfigs(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_service_rollouts(self) -> Callable[ - [servicemanager.ListServiceRolloutsRequest], - servicemanager.ListServiceRolloutsResponse]: - # 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._ListServiceRollouts(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_services(self) -> Callable[ - [servicemanager.ListServicesRequest], - servicemanager.ListServicesResponse]: - # 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._ListServices(self._session, self._host, self._interceptor) # type: ignore - - @property - def submit_config_source(self) -> Callable[ - [servicemanager.SubmitConfigSourceRequest], - 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._SubmitConfigSource(self._session, self._host, self._interceptor) # type: ignore - - @property - def undelete_service(self) -> Callable[ - [servicemanager.UndeleteServiceRequest], - 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._UndeleteService(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_iam_policy(self): - return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore - - class _GetIamPolicy(_BaseServiceManagerRestTransport._BaseGetIamPolicy, ServiceManagerRestStub): - def __hash__(self): - return hash("ServiceManagerRestTransport.GetIamPolicy") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: iam_policy_pb2.GetIamPolicyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> policy_pb2.Policy: - - r"""Call the get iam policy method over HTTP. - - Args: - request (iam_policy_pb2.GetIamPolicyRequest): - The request object for GetIamPolicy method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - policy_pb2.Policy: Response from GetIamPolicy method. - """ - - http_options = _BaseServiceManagerRestTransport._BaseGetIamPolicy._get_http_options() - - request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) - transcoded_request = _BaseServiceManagerRestTransport._BaseGetIamPolicy._get_transcoded_request(http_options, request) - - body = _BaseServiceManagerRestTransport._BaseGetIamPolicy._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseServiceManagerRestTransport._BaseGetIamPolicy._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.api.servicemanagement_v1.ServiceManagerClient.GetIamPolicy", - extra = { - "serviceName": "google.api.servicemanagement.v1.ServiceManager", - "rpcName": "GetIamPolicy", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = ServiceManagerRestTransport._GetIamPolicy._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - content = response.content.decode("utf-8") - resp = policy_pb2.Policy() - resp = json_format.Parse(content, resp) - resp = self._interceptor.post_get_iam_policy(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = json_format.MessageToJson(resp) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.api.servicemanagement_v1.ServiceManagerAsyncClient.GetIamPolicy", - extra = { - "serviceName": "google.api.servicemanagement.v1.ServiceManager", - "rpcName": "GetIamPolicy", - "httpResponse": http_response, - "metadata": http_response["headers"], - }, - ) - return resp - - @property - def set_iam_policy(self): - return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore - - class _SetIamPolicy(_BaseServiceManagerRestTransport._BaseSetIamPolicy, ServiceManagerRestStub): - def __hash__(self): - return hash("ServiceManagerRestTransport.SetIamPolicy") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: iam_policy_pb2.SetIamPolicyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> policy_pb2.Policy: - - r"""Call the set iam policy method over HTTP. - - Args: - request (iam_policy_pb2.SetIamPolicyRequest): - The request object for SetIamPolicy method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - policy_pb2.Policy: Response from SetIamPolicy method. - """ - - http_options = _BaseServiceManagerRestTransport._BaseSetIamPolicy._get_http_options() - - request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) - transcoded_request = _BaseServiceManagerRestTransport._BaseSetIamPolicy._get_transcoded_request(http_options, request) - - body = _BaseServiceManagerRestTransport._BaseSetIamPolicy._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseServiceManagerRestTransport._BaseSetIamPolicy._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.api.servicemanagement_v1.ServiceManagerClient.SetIamPolicy", - extra = { - "serviceName": "google.api.servicemanagement.v1.ServiceManager", - "rpcName": "SetIamPolicy", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = ServiceManagerRestTransport._SetIamPolicy._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - content = response.content.decode("utf-8") - resp = policy_pb2.Policy() - resp = json_format.Parse(content, resp) - resp = self._interceptor.post_set_iam_policy(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = json_format.MessageToJson(resp) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.api.servicemanagement_v1.ServiceManagerAsyncClient.SetIamPolicy", - extra = { - "serviceName": "google.api.servicemanagement.v1.ServiceManager", - "rpcName": "SetIamPolicy", - "httpResponse": http_response, - "metadata": http_response["headers"], - }, - ) - return resp - - @property - def test_iam_permissions(self): - return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore - - class _TestIamPermissions(_BaseServiceManagerRestTransport._BaseTestIamPermissions, ServiceManagerRestStub): - def __hash__(self): - return hash("ServiceManagerRestTransport.TestIamPermissions") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: iam_policy_pb2.TestIamPermissionsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - - r"""Call the test iam permissions method over HTTP. - - Args: - request (iam_policy_pb2.TestIamPermissionsRequest): - The request object for TestIamPermissions method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - iam_policy_pb2.TestIamPermissionsResponse: Response from TestIamPermissions method. - """ - - http_options = _BaseServiceManagerRestTransport._BaseTestIamPermissions._get_http_options() - - request, metadata = self._interceptor.pre_test_iam_permissions(request, metadata) - transcoded_request = _BaseServiceManagerRestTransport._BaseTestIamPermissions._get_transcoded_request(http_options, request) - - body = _BaseServiceManagerRestTransport._BaseTestIamPermissions._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseServiceManagerRestTransport._BaseTestIamPermissions._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.api.servicemanagement_v1.ServiceManagerClient.TestIamPermissions", - extra = { - "serviceName": "google.api.servicemanagement.v1.ServiceManager", - "rpcName": "TestIamPermissions", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = ServiceManagerRestTransport._TestIamPermissions._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - content = response.content.decode("utf-8") - resp = iam_policy_pb2.TestIamPermissionsResponse() - resp = json_format.Parse(content, resp) - resp = self._interceptor.post_test_iam_permissions(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = json_format.MessageToJson(resp) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.api.servicemanagement_v1.ServiceManagerAsyncClient.TestIamPermissions", - extra = { - "serviceName": "google.api.servicemanagement.v1.ServiceManager", - "rpcName": "TestIamPermissions", - "httpResponse": http_response, - "metadata": http_response["headers"], - }, - ) - return resp - - @property - def list_operations(self): - return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - - class _ListOperations(_BaseServiceManagerRestTransport._BaseListOperations, ServiceManagerRestStub): - def __hash__(self): - return hash("ServiceManagerRestTransport.ListOperations") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: operations_pb2.ListOperationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, Union[str, bytes]]]=(), - ) -> operations_pb2.ListOperationsResponse: - - r"""Call the list operations method over HTTP. - - Args: - request (operations_pb2.ListOperationsRequest): - The request object for ListOperations method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be - sent along with the request as metadata. Normally, each value must be of type `str`, - but for metadata keys ending with the suffix `-bin`, the corresponding values must - be of type `bytes`. - - Returns: - operations_pb2.ListOperationsResponse: Response from ListOperations method. - """ - - http_options = _BaseServiceManagerRestTransport._BaseListOperations._get_http_options() - - request, metadata = self._interceptor.pre_list_operations(request, metadata) - transcoded_request = _BaseServiceManagerRestTransport._BaseListOperations._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseServiceManagerRestTransport._BaseListOperations._get_query_params_json(transcoded_request) - - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - request_url = "{host}{uri}".format(host=self._host, uri=transcoded_request['uri']) - method = transcoded_request['method'] - try: - request_payload = json_format.MessageToJson(request) - except: - request_payload = None - http_request = { - "payload": request_payload, - "requestMethod": method, - "requestUrl": request_url, - "headers": dict(metadata), - } - _LOGGER.debug( - f"Sending request for google.api.servicemanagement_v1.ServiceManagerClient.ListOperations", - extra = { - "serviceName": "google.api.servicemanagement.v1.ServiceManager", - "rpcName": "ListOperations", - "httpRequest": http_request, - "metadata": http_request["headers"], - }, - ) - - # Send the request - response = ServiceManagerRestTransport._ListOperations._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - content = response.content.decode("utf-8") - resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(content, resp) - resp = self._interceptor.post_list_operations(resp) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(logging.DEBUG): # pragma: NO COVER - try: - response_payload = json_format.MessageToJson(resp) - except: - response_payload = None - http_response = { - "payload": response_payload, - "headers": dict(response.headers), - "status": response.status_code, - } - _LOGGER.debug( - "Received response for google.api.servicemanagement_v1.ServiceManagerAsyncClient.ListOperations", - extra = { - "serviceName": "google.api.servicemanagement.v1.ServiceManager", - "rpcName": "ListOperations", - "httpResponse": http_response, - "metadata": http_response["headers"], - }, - ) - return resp - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'ServiceManagerRestTransport', -) diff --git a/owl-bot-staging/google-cloud-service-management/v1/google/cloud/servicemanagement_v1/services/service_manager/transports/rest_base.py b/owl-bot-staging/google-cloud-service-management/v1/google/cloud/servicemanagement_v1/services/service_manager/transports/rest_base.py deleted file mode 100644 index 5d495f355da3..000000000000 --- a/owl-bot-staging/google-cloud-service-management/v1/google/cloud/servicemanagement_v1/services/service_manager/transports/rest_base.py +++ /dev/null @@ -1,753 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import json # type: ignore -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from .base import ServiceManagerTransport, DEFAULT_CLIENT_INFO - -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union - - -from google.api import service_pb2 # type: ignore -from google.cloud.servicemanagement_v1.types import resources -from google.cloud.servicemanagement_v1.types import servicemanager -from google.longrunning import operations_pb2 # type: ignore - - -class _BaseServiceManagerRestTransport(ServiceManagerTransport): - """Base REST backend transport for ServiceManager. - - Note: This class is not meant to be used directly. Use its sync and - async sub-classes instead. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends JSON representations of protocol buffers over HTTP/1.1 - """ - - def __init__(self, *, - host: str = 'servicemanagement.googleapis.com', - credentials: Optional[Any] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = 'https', - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - Args: - host (Optional[str]): - The hostname to connect to (default: 'servicemanagement.googleapis.com'). - credentials (Optional[Any]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) - if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER - - url_match_items = maybe_url_match.groupdict() - - host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host - - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience - ) - - class _BaseCreateService: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/services', - 'body': 'service', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = servicemanager.CreateServiceRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseServiceManagerRestTransport._BaseCreateService._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseCreateServiceConfig: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/services/{service_name}/configs', - 'body': 'service_config', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = servicemanager.CreateServiceConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseServiceManagerRestTransport._BaseCreateServiceConfig._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseCreateServiceRollout: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/services/{service_name}/rollouts', - 'body': 'rollout', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = servicemanager.CreateServiceRolloutRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseServiceManagerRestTransport._BaseCreateServiceRollout._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseDeleteService: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1/services/{service_name}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = servicemanager.DeleteServiceRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseServiceManagerRestTransport._BaseDeleteService._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGenerateConfigReport: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/services:generateConfigReport', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = servicemanager.GenerateConfigReportRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseServiceManagerRestTransport._BaseGenerateConfigReport._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetService: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/services/{service_name}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = servicemanager.GetServiceRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseServiceManagerRestTransport._BaseGetService._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetServiceConfig: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/services/{service_name}/configs/{config_id}', - }, - { - 'method': 'get', - 'uri': '/v1/services/{service_name}/config', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = servicemanager.GetServiceConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseServiceManagerRestTransport._BaseGetServiceConfig._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetServiceRollout: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/services/{service_name}/rollouts/{rollout_id}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = servicemanager.GetServiceRolloutRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseServiceManagerRestTransport._BaseGetServiceRollout._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseListServiceConfigs: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/services/{service_name}/configs', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = servicemanager.ListServiceConfigsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseServiceManagerRestTransport._BaseListServiceConfigs._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseListServiceRollouts: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "filter" : "", } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/services/{service_name}/rollouts', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = servicemanager.ListServiceRolloutsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseServiceManagerRestTransport._BaseListServiceRollouts._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseListServices: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/services', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = servicemanager.ListServicesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseSubmitConfigSource: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/services/{service_name}/configs:submit', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = servicemanager.SubmitConfigSourceRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseServiceManagerRestTransport._BaseSubmitConfigSource._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseUndeleteService: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/services/{service_name}:undelete', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = servicemanager.UndeleteServiceRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseServiceManagerRestTransport._BaseUndeleteService._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetIamPolicy: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{resource=services/*}:getIamPolicy', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1/{resource=services/*/consumers/*}:getIamPolicy', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - body = json.dumps(transcoded_request['body']) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - return query_params - - class _BaseSetIamPolicy: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{resource=services/*}:setIamPolicy', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1/{resource=services/*/consumers/*}:setIamPolicy', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - body = json.dumps(transcoded_request['body']) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - return query_params - - class _BaseTestIamPermissions: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{resource=services/*}:testIamPermissions', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1/{resource=services/*/consumers/*}:testIamPermissions', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - body = json.dumps(transcoded_request['body']) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - return query_params - - class _BaseListOperations: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/operations', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - return query_params - - -__all__=( - '_BaseServiceManagerRestTransport', -) diff --git a/owl-bot-staging/google-cloud-service-management/v1/google/cloud/servicemanagement_v1/types/__init__.py b/owl-bot-staging/google-cloud-service-management/v1/google/cloud/servicemanagement_v1/types/__init__.py deleted file mode 100644 index 9ea8b851e34d..000000000000 --- a/owl-bot-staging/google-cloud-service-management/v1/google/cloud/servicemanagement_v1/types/__init__.py +++ /dev/null @@ -1,78 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 .resources import ( - ChangeReport, - ConfigFile, - ConfigRef, - ConfigSource, - Diagnostic, - ManagedService, - OperationMetadata, - Rollout, -) -from .servicemanager import ( - CreateServiceConfigRequest, - CreateServiceRequest, - CreateServiceRolloutRequest, - DeleteServiceRequest, - EnableServiceResponse, - GenerateConfigReportRequest, - GenerateConfigReportResponse, - GetServiceConfigRequest, - GetServiceRequest, - GetServiceRolloutRequest, - ListServiceConfigsRequest, - ListServiceConfigsResponse, - ListServiceRolloutsRequest, - ListServiceRolloutsResponse, - ListServicesRequest, - ListServicesResponse, - SubmitConfigSourceRequest, - SubmitConfigSourceResponse, - UndeleteServiceRequest, - UndeleteServiceResponse, -) - -__all__ = ( - 'ChangeReport', - 'ConfigFile', - 'ConfigRef', - 'ConfigSource', - 'Diagnostic', - 'ManagedService', - 'OperationMetadata', - 'Rollout', - 'CreateServiceConfigRequest', - 'CreateServiceRequest', - 'CreateServiceRolloutRequest', - 'DeleteServiceRequest', - 'EnableServiceResponse', - 'GenerateConfigReportRequest', - 'GenerateConfigReportResponse', - 'GetServiceConfigRequest', - 'GetServiceRequest', - 'GetServiceRolloutRequest', - 'ListServiceConfigsRequest', - 'ListServiceConfigsResponse', - 'ListServiceRolloutsRequest', - 'ListServiceRolloutsResponse', - 'ListServicesRequest', - 'ListServicesResponse', - 'SubmitConfigSourceRequest', - 'SubmitConfigSourceResponse', - 'UndeleteServiceRequest', - 'UndeleteServiceResponse', -) diff --git a/owl-bot-staging/google-cloud-service-management/v1/google/cloud/servicemanagement_v1/types/resources.py b/owl-bot-staging/google-cloud-service-management/v1/google/cloud/servicemanagement_v1/types/resources.py deleted file mode 100644 index 05a672471944..000000000000 --- a/owl-bot-staging/google-cloud-service-management/v1/google/cloud/servicemanagement_v1/types/resources.py +++ /dev/null @@ -1,490 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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.api import config_change_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.api.servicemanagement.v1', - manifest={ - 'ManagedService', - 'OperationMetadata', - 'Diagnostic', - 'ConfigSource', - 'ConfigFile', - 'ConfigRef', - 'ChangeReport', - 'Rollout', - }, -) - - -class ManagedService(proto.Message): - r"""The full representation of a Service that is managed by - Google Service Management. - - Attributes: - service_name (str): - The name of the service. See the - `overview `__ - for naming requirements. - producer_project_id (str): - ID of the project that produces and owns this - service. - """ - - service_name: str = proto.Field( - proto.STRING, - number=2, - ) - producer_project_id: str = proto.Field( - proto.STRING, - number=3, - ) - - -class OperationMetadata(proto.Message): - r"""The metadata associated with a long running operation - resource. - - Attributes: - resource_names (MutableSequence[str]): - The full name of the resources that this - operation is directly associated with. - steps (MutableSequence[google.cloud.servicemanagement_v1.types.OperationMetadata.Step]): - Detailed status information for each step. - The order is undetermined. - progress_percentage (int): - Percentage of completion of this operation, - ranging from 0 to 100. - start_time (google.protobuf.timestamp_pb2.Timestamp): - The start time of the operation. - """ - class Status(proto.Enum): - r"""Code describes the status of the operation (or one of its - steps). - - Values: - STATUS_UNSPECIFIED (0): - Unspecifed code. - DONE (1): - The operation or step has completed without - errors. - NOT_STARTED (2): - The operation or step has not started yet. - IN_PROGRESS (3): - The operation or step is in progress. - FAILED (4): - The operation or step has completed with - errors. If the operation is rollbackable, the - rollback completed with errors too. - CANCELLED (5): - The operation or step has completed with - cancellation. - """ - STATUS_UNSPECIFIED = 0 - DONE = 1 - NOT_STARTED = 2 - IN_PROGRESS = 3 - FAILED = 4 - CANCELLED = 5 - - class Step(proto.Message): - r"""Represents the status of one operation step. - - Attributes: - description (str): - The short description of the step. - status (google.cloud.servicemanagement_v1.types.OperationMetadata.Status): - The status code. - """ - - description: str = proto.Field( - proto.STRING, - number=2, - ) - status: 'OperationMetadata.Status' = proto.Field( - proto.ENUM, - number=4, - enum='OperationMetadata.Status', - ) - - resource_names: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=1, - ) - steps: MutableSequence[Step] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=Step, - ) - progress_percentage: int = proto.Field( - proto.INT32, - number=3, - ) - start_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - - -class Diagnostic(proto.Message): - r"""Represents a diagnostic message (error or warning) - - Attributes: - location (str): - File name and line number of the error or - warning. - kind (google.cloud.servicemanagement_v1.types.Diagnostic.Kind): - The kind of diagnostic information provided. - message (str): - Message describing the error or warning. - """ - class Kind(proto.Enum): - r"""The kind of diagnostic information possible. - - Values: - WARNING (0): - Warnings and errors - ERROR (1): - Only errors - """ - WARNING = 0 - ERROR = 1 - - location: str = proto.Field( - proto.STRING, - number=1, - ) - kind: Kind = proto.Field( - proto.ENUM, - number=2, - enum=Kind, - ) - message: str = proto.Field( - proto.STRING, - number=3, - ) - - -class ConfigSource(proto.Message): - r"""Represents a source file which is used to generate the service - configuration defined by ``google.api.Service``. - - Attributes: - id (str): - A unique ID for a specific instance of this - message, typically assigned by the client for - tracking purpose. If empty, the server may - choose to generate one instead. - files (MutableSequence[google.cloud.servicemanagement_v1.types.ConfigFile]): - Set of source configuration files that are used to generate - a service configuration (``google.api.Service``). - """ - - id: str = proto.Field( - proto.STRING, - number=5, - ) - files: MutableSequence['ConfigFile'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='ConfigFile', - ) - - -class ConfigFile(proto.Message): - r"""Generic specification of a source configuration file - - Attributes: - file_path (str): - The file name of the configuration file (full - or relative path). - file_contents (bytes): - The bytes that constitute the file. - file_type (google.cloud.servicemanagement_v1.types.ConfigFile.FileType): - The type of configuration file this - represents. - """ - class FileType(proto.Enum): - r""" - - Values: - FILE_TYPE_UNSPECIFIED (0): - Unknown file type. - SERVICE_CONFIG_YAML (1): - YAML-specification of service. - OPEN_API_JSON (2): - OpenAPI specification, serialized in JSON. - OPEN_API_YAML (3): - OpenAPI specification, serialized in YAML. - FILE_DESCRIPTOR_SET_PROTO (4): - FileDescriptorSet, generated by protoc. - - To generate, use protoc with imports and source info - included. For an example test.proto file, the following - command would put the value in a new file named out.pb. - - $protoc --include_imports --include_source_info test.proto - -o out.pb - PROTO_FILE (6): - Uncompiled Proto file. Used for storage and display purposes - only, currently server-side compilation is not supported. - Should match the inputs to 'protoc' command used to - generated FILE_DESCRIPTOR_SET_PROTO. A file of this type can - only be included if at least one file of type - FILE_DESCRIPTOR_SET_PROTO is included. - """ - FILE_TYPE_UNSPECIFIED = 0 - SERVICE_CONFIG_YAML = 1 - OPEN_API_JSON = 2 - OPEN_API_YAML = 3 - FILE_DESCRIPTOR_SET_PROTO = 4 - PROTO_FILE = 6 - - file_path: str = proto.Field( - proto.STRING, - number=1, - ) - file_contents: bytes = proto.Field( - proto.BYTES, - number=3, - ) - file_type: FileType = proto.Field( - proto.ENUM, - number=4, - enum=FileType, - ) - - -class ConfigRef(proto.Message): - r"""Represents a service configuration with its name and id. - - Attributes: - name (str): - Resource name of a service config. It must - have the following format: "services/{service - name}/configs/{config id}". - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ChangeReport(proto.Message): - r"""Change report associated with a particular service - configuration. - It contains a list of ConfigChanges based on the comparison - between two service configurations. - - Attributes: - config_changes (MutableSequence[google.api.config_change_pb2.ConfigChange]): - List of changes between two service configurations. The - changes will be alphabetically sorted based on the - identifier of each change. A ConfigChange identifier is a - dot separated path to the configuration. Example: - visibility.rules[selector='LibraryService.CreateBook'].restriction - """ - - config_changes: MutableSequence[config_change_pb2.ConfigChange] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=config_change_pb2.ConfigChange, - ) - - -class Rollout(proto.Message): - r"""A rollout resource that defines how service configuration - versions are pushed to control plane systems. Typically, you - create a new version of the service config, and then create a - Rollout to push the service config. - - 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: - rollout_id (str): - Optional. Unique identifier of this Rollout. Must be no - longer than 63 characters and only lower case letters, - digits, '.', '_' and '-' are allowed. - - If not specified by client, the server will generate one. - The generated id will have the form of , where "date" is the - create date in ISO 8601 format. "revision number" is a - monotonically increasing positive number that is reset every - day for each service. An example of the generated rollout_id - is '2016-02-16r1' - create_time (google.protobuf.timestamp_pb2.Timestamp): - Creation time of the rollout. Readonly. - created_by (str): - The user who created the Rollout. Readonly. - status (google.cloud.servicemanagement_v1.types.Rollout.RolloutStatus): - The status of this rollout. Readonly. In case - of a failed rollout, the system will - automatically rollback to the current Rollout - version. Readonly. - traffic_percent_strategy (google.cloud.servicemanagement_v1.types.Rollout.TrafficPercentStrategy): - Google Service Control selects service - configurations based on traffic percentage. - - This field is a member of `oneof`_ ``strategy``. - delete_service_strategy (google.cloud.servicemanagement_v1.types.Rollout.DeleteServiceStrategy): - The strategy associated with a rollout to delete a - ``ManagedService``. Readonly. - - This field is a member of `oneof`_ ``strategy``. - service_name (str): - The name of the service associated with this - Rollout. - """ - class RolloutStatus(proto.Enum): - r"""Status of a Rollout. - - Values: - ROLLOUT_STATUS_UNSPECIFIED (0): - No status specified. - IN_PROGRESS (1): - The Rollout is in progress. - SUCCESS (2): - The Rollout has completed successfully. - CANCELLED (3): - The Rollout has been cancelled. This can - happen if you have overlapping Rollout pushes, - and the previous ones will be cancelled. - FAILED (4): - The Rollout has failed and the rollback - attempt has failed too. - PENDING (5): - The Rollout has not started yet and is - pending for execution. - FAILED_ROLLED_BACK (6): - The Rollout has failed and rolled back to the - previous successful Rollout. - """ - ROLLOUT_STATUS_UNSPECIFIED = 0 - IN_PROGRESS = 1 - SUCCESS = 2 - CANCELLED = 3 - FAILED = 4 - PENDING = 5 - FAILED_ROLLED_BACK = 6 - - class TrafficPercentStrategy(proto.Message): - r"""Strategy that specifies how clients of Google Service Controller - want to send traffic to use different config versions. This is - generally used by API proxy to split traffic based on your - configured percentage for each config version. - - One example of how to gradually rollout a new service configuration - using this strategy: Day 1 - - :: - - Rollout { - id: "example.googleapis.com/rollout_20160206" - traffic_percent_strategy { - percentages: { - "example.googleapis.com/20160201": 70.00 - "example.googleapis.com/20160206": 30.00 - } - } - } - - Day 2 - - :: - - Rollout { - id: "example.googleapis.com/rollout_20160207" - traffic_percent_strategy: { - percentages: { - "example.googleapis.com/20160206": 100.00 - } - } - } - - Attributes: - percentages (MutableMapping[str, float]): - Maps service configuration IDs to their - corresponding traffic percentage. Key is the - service configuration ID, Value is the traffic - percentage which must be greater than 0.0 and - the sum must equal to 100.0. - """ - - percentages: MutableMapping[str, float] = proto.MapField( - proto.STRING, - proto.DOUBLE, - number=1, - ) - - class DeleteServiceStrategy(proto.Message): - r"""Strategy used to delete a service. This strategy is a - placeholder only used by the system generated rollout to delete - a service. - - """ - - rollout_id: str = proto.Field( - proto.STRING, - number=1, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - created_by: str = proto.Field( - proto.STRING, - number=3, - ) - status: RolloutStatus = proto.Field( - proto.ENUM, - number=4, - enum=RolloutStatus, - ) - traffic_percent_strategy: TrafficPercentStrategy = proto.Field( - proto.MESSAGE, - number=5, - oneof='strategy', - message=TrafficPercentStrategy, - ) - delete_service_strategy: DeleteServiceStrategy = proto.Field( - proto.MESSAGE, - number=200, - oneof='strategy', - message=DeleteServiceStrategy, - ) - service_name: str = proto.Field( - proto.STRING, - number=8, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-service-management/v1/google/cloud/servicemanagement_v1/types/servicemanager.py b/owl-bot-staging/google-cloud-service-management/v1/google/cloud/servicemanagement_v1/types/servicemanager.py deleted file mode 100644 index 445cf6b0ca2d..000000000000 --- a/owl-bot-staging/google-cloud-service-management/v1/google/cloud/servicemanagement_v1/types/servicemanager.py +++ /dev/null @@ -1,576 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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.api import service_pb2 # type: ignore -from google.cloud.servicemanagement_v1.types import resources -from google.protobuf import any_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.api.servicemanagement.v1', - manifest={ - 'ListServicesRequest', - 'ListServicesResponse', - 'GetServiceRequest', - 'CreateServiceRequest', - 'DeleteServiceRequest', - 'UndeleteServiceRequest', - 'UndeleteServiceResponse', - 'GetServiceConfigRequest', - 'ListServiceConfigsRequest', - 'ListServiceConfigsResponse', - 'CreateServiceConfigRequest', - 'SubmitConfigSourceRequest', - 'SubmitConfigSourceResponse', - 'CreateServiceRolloutRequest', - 'ListServiceRolloutsRequest', - 'ListServiceRolloutsResponse', - 'GetServiceRolloutRequest', - 'EnableServiceResponse', - 'GenerateConfigReportRequest', - 'GenerateConfigReportResponse', - }, -) - - -class ListServicesRequest(proto.Message): - r"""Request message for ``ListServices`` method. - - Attributes: - producer_project_id (str): - Include services produced by the specified - project. - page_size (int): - The max number of items to include in the - response list. Page size is 50 if not specified. - Maximum value is 500. - page_token (str): - Token identifying which result to start with; - returned by a previous list call. - consumer_id (str): - Include services consumed by the specified consumer. - - The Google Service Management implementation accepts the - following forms: - - - project: - """ - - producer_project_id: str = proto.Field( - proto.STRING, - number=1, - ) - page_size: int = proto.Field( - proto.INT32, - number=5, - ) - page_token: str = proto.Field( - proto.STRING, - number=6, - ) - consumer_id: str = proto.Field( - proto.STRING, - number=7, - ) - - -class ListServicesResponse(proto.Message): - r"""Response message for ``ListServices`` method. - - Attributes: - services (MutableSequence[google.cloud.servicemanagement_v1.types.ManagedService]): - The returned services will only have the name - field set. - next_page_token (str): - Token that can be passed to ``ListServices`` to resume a - paginated query. - """ - - @property - def raw_page(self): - return self - - services: MutableSequence[resources.ManagedService] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=resources.ManagedService, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class GetServiceRequest(proto.Message): - r"""Request message for ``GetService`` method. - - Attributes: - service_name (str): - Required. The name of the service. See the - ``ServiceManager`` overview for naming requirements. For - example: ``example.googleapis.com``. - """ - - service_name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class CreateServiceRequest(proto.Message): - r"""Request message for CreateService method. - - Attributes: - service (google.cloud.servicemanagement_v1.types.ManagedService): - Required. Initial values for the service - resource. - """ - - service: resources.ManagedService = proto.Field( - proto.MESSAGE, - number=1, - message=resources.ManagedService, - ) - - -class DeleteServiceRequest(proto.Message): - r"""Request message for DeleteService method. - - Attributes: - service_name (str): - Required. The name of the service. See the - `overview `__ - for naming requirements. For example: - ``example.googleapis.com``. - """ - - service_name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class UndeleteServiceRequest(proto.Message): - r"""Request message for UndeleteService method. - - Attributes: - service_name (str): - Required. The name of the service. See the - `overview `__ - for naming requirements. For example: - ``example.googleapis.com``. - """ - - service_name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class UndeleteServiceResponse(proto.Message): - r"""Response message for UndeleteService method. - - Attributes: - service (google.cloud.servicemanagement_v1.types.ManagedService): - Revived service resource. - """ - - service: resources.ManagedService = proto.Field( - proto.MESSAGE, - number=1, - message=resources.ManagedService, - ) - - -class GetServiceConfigRequest(proto.Message): - r"""Request message for GetServiceConfig method. - - Attributes: - service_name (str): - Required. The name of the service. See the - `overview `__ - for naming requirements. For example: - ``example.googleapis.com``. - config_id (str): - Required. The id of the service configuration resource. - - This field must be specified for the server to return all - fields, including ``SourceInfo``. - view (google.cloud.servicemanagement_v1.types.GetServiceConfigRequest.ConfigView): - Specifies which parts of the Service Config - should be returned in the response. - """ - class ConfigView(proto.Enum): - r""" - - Values: - BASIC (0): - Server response includes all fields except - SourceInfo. - FULL (1): - Server response includes all fields including - SourceInfo. SourceFiles are of type - 'google.api.servicemanagement.v1.ConfigFile' and - are only available for configs created using the - SubmitConfigSource method. - """ - BASIC = 0 - FULL = 1 - - service_name: str = proto.Field( - proto.STRING, - number=1, - ) - config_id: str = proto.Field( - proto.STRING, - number=2, - ) - view: ConfigView = proto.Field( - proto.ENUM, - number=3, - enum=ConfigView, - ) - - -class ListServiceConfigsRequest(proto.Message): - r"""Request message for ListServiceConfigs method. - - Attributes: - service_name (str): - Required. The name of the service. See the - `overview `__ - for naming requirements. For example: - ``example.googleapis.com``. - page_token (str): - The token of the page to retrieve. - page_size (int): - The max number of items to include in the - response list. Page size is 50 if not specified. - Maximum value is 100. - """ - - service_name: str = proto.Field( - proto.STRING, - number=1, - ) - page_token: str = proto.Field( - proto.STRING, - number=2, - ) - page_size: int = proto.Field( - proto.INT32, - number=3, - ) - - -class ListServiceConfigsResponse(proto.Message): - r"""Response message for ListServiceConfigs method. - - Attributes: - service_configs (MutableSequence[google.api.service_pb2.Service]): - The list of service configuration resources. - next_page_token (str): - The token of the next page of results. - """ - - @property - def raw_page(self): - return self - - service_configs: MutableSequence[service_pb2.Service] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=service_pb2.Service, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class CreateServiceConfigRequest(proto.Message): - r"""Request message for CreateServiceConfig method. - - Attributes: - service_name (str): - Required. The name of the service. See the - `overview `__ - for naming requirements. For example: - ``example.googleapis.com``. - service_config (google.api.service_pb2.Service): - Required. The service configuration resource. - """ - - service_name: str = proto.Field( - proto.STRING, - number=1, - ) - service_config: service_pb2.Service = proto.Field( - proto.MESSAGE, - number=2, - message=service_pb2.Service, - ) - - -class SubmitConfigSourceRequest(proto.Message): - r"""Request message for SubmitConfigSource method. - - Attributes: - service_name (str): - Required. The name of the service. See the - `overview `__ - for naming requirements. For example: - ``example.googleapis.com``. - config_source (google.cloud.servicemanagement_v1.types.ConfigSource): - Required. The source configuration for the - service. - validate_only (bool): - Optional. If set, this will result in the generation of a - ``google.api.Service`` configuration based on the - ``ConfigSource`` provided, but the generated config and the - sources will NOT be persisted. - """ - - service_name: str = proto.Field( - proto.STRING, - number=1, - ) - config_source: resources.ConfigSource = proto.Field( - proto.MESSAGE, - number=2, - message=resources.ConfigSource, - ) - validate_only: bool = proto.Field( - proto.BOOL, - number=3, - ) - - -class SubmitConfigSourceResponse(proto.Message): - r"""Response message for SubmitConfigSource method. - - Attributes: - service_config (google.api.service_pb2.Service): - The generated service configuration. - """ - - service_config: service_pb2.Service = proto.Field( - proto.MESSAGE, - number=1, - message=service_pb2.Service, - ) - - -class CreateServiceRolloutRequest(proto.Message): - r"""Request message for 'CreateServiceRollout' - - Attributes: - service_name (str): - Required. The name of the service. See the - `overview `__ - for naming requirements. For example: - ``example.googleapis.com``. - rollout (google.cloud.servicemanagement_v1.types.Rollout): - Required. The rollout resource. The ``service_name`` field - is output only. - """ - - service_name: str = proto.Field( - proto.STRING, - number=1, - ) - rollout: resources.Rollout = proto.Field( - proto.MESSAGE, - number=2, - message=resources.Rollout, - ) - - -class ListServiceRolloutsRequest(proto.Message): - r"""Request message for 'ListServiceRollouts' - - Attributes: - service_name (str): - Required. The name of the service. See the - `overview `__ - for naming requirements. For example: - ``example.googleapis.com``. - page_token (str): - The token of the page to retrieve. - page_size (int): - The max number of items to include in the - response list. Page size is 50 if not specified. - Maximum value is 100. - filter (str): - Required. Use ``filter`` to return subset of rollouts. The - following filters are supported: - - -- By [status] - [google.api.servicemanagement.v1.Rollout.RolloutStatus]. For - example, ``filter='status=SUCCESS'`` - - -- By [strategy] - [google.api.servicemanagement.v1.Rollout.strategy]. For - example, ``filter='strategy=TrafficPercentStrategy'`` - """ - - service_name: str = proto.Field( - proto.STRING, - number=1, - ) - page_token: str = proto.Field( - proto.STRING, - number=2, - ) - page_size: int = proto.Field( - proto.INT32, - number=3, - ) - filter: str = proto.Field( - proto.STRING, - number=4, - ) - - -class ListServiceRolloutsResponse(proto.Message): - r"""Response message for ListServiceRollouts method. - - Attributes: - rollouts (MutableSequence[google.cloud.servicemanagement_v1.types.Rollout]): - The list of rollout resources. - next_page_token (str): - The token of the next page of results. - """ - - @property - def raw_page(self): - return self - - rollouts: MutableSequence[resources.Rollout] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=resources.Rollout, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class GetServiceRolloutRequest(proto.Message): - r"""Request message for GetServiceRollout method. - - Attributes: - service_name (str): - Required. The name of the service. See the - `overview `__ - for naming requirements. For example: - ``example.googleapis.com``. - rollout_id (str): - Required. The id of the rollout resource. - """ - - service_name: str = proto.Field( - proto.STRING, - number=1, - ) - rollout_id: str = proto.Field( - proto.STRING, - number=2, - ) - - -class EnableServiceResponse(proto.Message): - r"""Operation payload for EnableService method. - """ - - -class GenerateConfigReportRequest(proto.Message): - r"""Request message for GenerateConfigReport method. - - Attributes: - new_config (google.protobuf.any_pb2.Any): - Required. Service configuration for which we want to - generate the report. For this version of API, the supported - types are - [google.api.servicemanagement.v1.ConfigRef][google.api.servicemanagement.v1.ConfigRef], - [google.api.servicemanagement.v1.ConfigSource][google.api.servicemanagement.v1.ConfigSource], - and [google.api.Service][google.api.Service] - old_config (google.protobuf.any_pb2.Any): - Optional. Service configuration against which the comparison - will be done. For this version of API, the supported types - are - [google.api.servicemanagement.v1.ConfigRef][google.api.servicemanagement.v1.ConfigRef], - [google.api.servicemanagement.v1.ConfigSource][google.api.servicemanagement.v1.ConfigSource], - and [google.api.Service][google.api.Service] - """ - - new_config: any_pb2.Any = proto.Field( - proto.MESSAGE, - number=1, - message=any_pb2.Any, - ) - old_config: any_pb2.Any = proto.Field( - proto.MESSAGE, - number=2, - message=any_pb2.Any, - ) - - -class GenerateConfigReportResponse(proto.Message): - r"""Response message for GenerateConfigReport method. - - Attributes: - service_name (str): - Name of the service this report belongs to. - id (str): - ID of the service configuration this report - belongs to. - change_reports (MutableSequence[google.cloud.servicemanagement_v1.types.ChangeReport]): - list of ChangeReport, each corresponding to - comparison between two service configurations. - diagnostics (MutableSequence[google.cloud.servicemanagement_v1.types.Diagnostic]): - Errors / Linter warnings associated with the - service definition this report - belongs to. - """ - - service_name: str = proto.Field( - proto.STRING, - number=1, - ) - id: str = proto.Field( - proto.STRING, - number=2, - ) - change_reports: MutableSequence[resources.ChangeReport] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=resources.ChangeReport, - ) - diagnostics: MutableSequence[resources.Diagnostic] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message=resources.Diagnostic, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-service-management/v1/mypy.ini b/owl-bot-staging/google-cloud-service-management/v1/mypy.ini deleted file mode 100644 index 574c5aed394b..000000000000 --- a/owl-bot-staging/google-cloud-service-management/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-service-management/v1/noxfile.py b/owl-bot-staging/google-cloud-service-management/v1/noxfile.py deleted file mode 100644 index 22d41d9f843e..000000000000 --- a/owl-bot-staging/google-cloud-service-management/v1/noxfile.py +++ /dev/null @@ -1,280 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import pathlib -import re -import shutil -import subprocess -import sys - - -import nox # type: ignore - -ALL_PYTHON = [ - "3.7", - "3.8", - "3.9", - "3.10", - "3.11", - "3.12", - "3.13", -] - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = 'google-cloud-service-management' - -BLACK_VERSION = "black==22.3.0" -BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] -DEFAULT_PYTHON_VERSION = "3.13" - -nox.sessions = [ - "unit", - "cover", - "mypy", - "check_lower_bounds" - # exclude update_lower_bounds from default - "docs", - "blacken", - "lint", - "prerelease_deps", -] - -@nox.session(python=ALL_PYTHON) -@nox.parametrize( - "protobuf_implementation", - [ "python", "upb", "cpp" ], -) -def unit(session, protobuf_implementation): - """Run the unit test suite.""" - - if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"): - session.skip("cpp implementation is not supported in python 3.11+") - - session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') - session.install('-e', '.', "-c", f"testing/constraints-{session.python}.txt") - - # Remove the 'cpp' implementation once support for Protobuf 3.x is dropped. - # The 'cpp' implementation requires Protobuf<4. - if protobuf_implementation == "cpp": - session.install("protobuf<4") - - session.run( - 'py.test', - '--quiet', - '--cov=google/cloud/servicemanagement_v1/', - '--cov=tests/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)), - env={ - "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, - }, - ) - -@nox.session(python=ALL_PYTHON[-1]) -@nox.parametrize( - "protobuf_implementation", - [ "python", "upb", "cpp" ], -) -def prerelease_deps(session, protobuf_implementation): - """Run the unit test suite against pre-release versions of dependencies.""" - - if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"): - session.skip("cpp implementation is not supported in python 3.11+") - - # Install test environment dependencies - session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') - - # Install the package without dependencies - session.install('-e', '.', '--no-deps') - - # We test the minimum dependency versions using the minimum Python - # version so the lowest python runtime that we test has a corresponding constraints - # file, located at `testing/constraints--.txt`, which contains all of the - # dependencies and extras. - with open( - CURRENT_DIRECTORY - / "testing" - / f"constraints-{ALL_PYTHON[0]}.txt", - encoding="utf-8", - ) as constraints_file: - constraints_text = constraints_file.read() - - # Ignore leading whitespace and comment lines. - constraints_deps = [ - match.group(1) - for match in re.finditer( - r"^\s*(\S+)(?===\S+)", constraints_text, flags=re.MULTILINE - ) - ] - - session.install(*constraints_deps) - - prerel_deps = [ - "googleapis-common-protos", - "google-api-core", - "google-auth", - # Exclude grpcio!=1.67.0rc1 which does not support python 3.13 - "grpcio!=1.67.0rc1", - "grpcio-status", - "protobuf", - "proto-plus", - ] - - for dep in prerel_deps: - session.install("--pre", "--no-deps", "--upgrade", dep) - - # Remaining dependencies - other_deps = [ - "requests", - ] - session.install(*other_deps) - - # Print out prerelease package versions - - session.run("python", "-c", "import google.api_core; print(google.api_core.__version__)") - session.run("python", "-c", "import google.auth; print(google.auth.__version__)") - session.run("python", "-c", "import grpc; print(grpc.__version__)") - session.run( - "python", "-c", "import google.protobuf; print(google.protobuf.__version__)" - ) - session.run( - "python", "-c", "import proto; print(proto.__version__)" - ) - - session.run( - 'py.test', - '--quiet', - '--cov=google/cloud/servicemanagement_v1/', - '--cov=tests/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)), - env={ - "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, - }, - ) - - -@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-service-management/v1/samples/generated_samples/servicemanagement_v1_generated_service_manager_create_service_async.py b/owl-bot-staging/google-cloud-service-management/v1/samples/generated_samples/servicemanagement_v1_generated_service_manager_create_service_async.py deleted file mode 100644 index fc2a7817911d..000000000000 --- a/owl-bot-staging/google-cloud-service-management/v1/samples/generated_samples/servicemanagement_v1_generated_service_manager_create_service_async.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateService -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-service-management - - -# [START servicemanagement_v1_generated_ServiceManager_CreateService_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 servicemanagement_v1 - - -async def sample_create_service(): - # Create a client - client = servicemanagement_v1.ServiceManagerAsyncClient() - - # Initialize request argument(s) - request = servicemanagement_v1.CreateServiceRequest( - ) - - # Make the request - operation = client.create_service(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END servicemanagement_v1_generated_ServiceManager_CreateService_async] diff --git a/owl-bot-staging/google-cloud-service-management/v1/samples/generated_samples/servicemanagement_v1_generated_service_manager_create_service_config_async.py b/owl-bot-staging/google-cloud-service-management/v1/samples/generated_samples/servicemanagement_v1_generated_service_manager_create_service_config_async.py deleted file mode 100644 index 8704f8a996b4..000000000000 --- a/owl-bot-staging/google-cloud-service-management/v1/samples/generated_samples/servicemanagement_v1_generated_service_manager_create_service_config_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateServiceConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-service-management - - -# [START servicemanagement_v1_generated_ServiceManager_CreateServiceConfig_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 servicemanagement_v1 - - -async def sample_create_service_config(): - # Create a client - client = servicemanagement_v1.ServiceManagerAsyncClient() - - # Initialize request argument(s) - request = servicemanagement_v1.CreateServiceConfigRequest( - service_name="service_name_value", - ) - - # Make the request - response = await client.create_service_config(request=request) - - # Handle the response - print(response) - -# [END servicemanagement_v1_generated_ServiceManager_CreateServiceConfig_async] diff --git a/owl-bot-staging/google-cloud-service-management/v1/samples/generated_samples/servicemanagement_v1_generated_service_manager_create_service_config_sync.py b/owl-bot-staging/google-cloud-service-management/v1/samples/generated_samples/servicemanagement_v1_generated_service_manager_create_service_config_sync.py deleted file mode 100644 index 1c92619b85c7..000000000000 --- a/owl-bot-staging/google-cloud-service-management/v1/samples/generated_samples/servicemanagement_v1_generated_service_manager_create_service_config_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateServiceConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-service-management - - -# [START servicemanagement_v1_generated_ServiceManager_CreateServiceConfig_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 servicemanagement_v1 - - -def sample_create_service_config(): - # Create a client - client = servicemanagement_v1.ServiceManagerClient() - - # Initialize request argument(s) - request = servicemanagement_v1.CreateServiceConfigRequest( - service_name="service_name_value", - ) - - # Make the request - response = client.create_service_config(request=request) - - # Handle the response - print(response) - -# [END servicemanagement_v1_generated_ServiceManager_CreateServiceConfig_sync] diff --git a/owl-bot-staging/google-cloud-service-management/v1/samples/generated_samples/servicemanagement_v1_generated_service_manager_create_service_rollout_async.py b/owl-bot-staging/google-cloud-service-management/v1/samples/generated_samples/servicemanagement_v1_generated_service_manager_create_service_rollout_async.py deleted file mode 100644 index 2b6b9a83c219..000000000000 --- a/owl-bot-staging/google-cloud-service-management/v1/samples/generated_samples/servicemanagement_v1_generated_service_manager_create_service_rollout_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateServiceRollout -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-service-management - - -# [START servicemanagement_v1_generated_ServiceManager_CreateServiceRollout_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 servicemanagement_v1 - - -async def sample_create_service_rollout(): - # Create a client - client = servicemanagement_v1.ServiceManagerAsyncClient() - - # Initialize request argument(s) - request = servicemanagement_v1.CreateServiceRolloutRequest( - service_name="service_name_value", - ) - - # Make the request - operation = client.create_service_rollout(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END servicemanagement_v1_generated_ServiceManager_CreateServiceRollout_async] diff --git a/owl-bot-staging/google-cloud-service-management/v1/samples/generated_samples/servicemanagement_v1_generated_service_manager_create_service_rollout_sync.py b/owl-bot-staging/google-cloud-service-management/v1/samples/generated_samples/servicemanagement_v1_generated_service_manager_create_service_rollout_sync.py deleted file mode 100644 index a9f3aff2d428..000000000000 --- a/owl-bot-staging/google-cloud-service-management/v1/samples/generated_samples/servicemanagement_v1_generated_service_manager_create_service_rollout_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateServiceRollout -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-service-management - - -# [START servicemanagement_v1_generated_ServiceManager_CreateServiceRollout_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 servicemanagement_v1 - - -def sample_create_service_rollout(): - # Create a client - client = servicemanagement_v1.ServiceManagerClient() - - # Initialize request argument(s) - request = servicemanagement_v1.CreateServiceRolloutRequest( - service_name="service_name_value", - ) - - # Make the request - operation = client.create_service_rollout(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END servicemanagement_v1_generated_ServiceManager_CreateServiceRollout_sync] diff --git a/owl-bot-staging/google-cloud-service-management/v1/samples/generated_samples/servicemanagement_v1_generated_service_manager_create_service_sync.py b/owl-bot-staging/google-cloud-service-management/v1/samples/generated_samples/servicemanagement_v1_generated_service_manager_create_service_sync.py deleted file mode 100644 index 00293a121ea9..000000000000 --- a/owl-bot-staging/google-cloud-service-management/v1/samples/generated_samples/servicemanagement_v1_generated_service_manager_create_service_sync.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateService -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-service-management - - -# [START servicemanagement_v1_generated_ServiceManager_CreateService_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 servicemanagement_v1 - - -def sample_create_service(): - # Create a client - client = servicemanagement_v1.ServiceManagerClient() - - # Initialize request argument(s) - request = servicemanagement_v1.CreateServiceRequest( - ) - - # Make the request - operation = client.create_service(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END servicemanagement_v1_generated_ServiceManager_CreateService_sync] diff --git a/owl-bot-staging/google-cloud-service-management/v1/samples/generated_samples/servicemanagement_v1_generated_service_manager_delete_service_async.py b/owl-bot-staging/google-cloud-service-management/v1/samples/generated_samples/servicemanagement_v1_generated_service_manager_delete_service_async.py deleted file mode 100644 index 2aae72f239fb..000000000000 --- a/owl-bot-staging/google-cloud-service-management/v1/samples/generated_samples/servicemanagement_v1_generated_service_manager_delete_service_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteService -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-service-management - - -# [START servicemanagement_v1_generated_ServiceManager_DeleteService_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 servicemanagement_v1 - - -async def sample_delete_service(): - # Create a client - client = servicemanagement_v1.ServiceManagerAsyncClient() - - # Initialize request argument(s) - request = servicemanagement_v1.DeleteServiceRequest( - service_name="service_name_value", - ) - - # Make the request - operation = client.delete_service(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END servicemanagement_v1_generated_ServiceManager_DeleteService_async] diff --git a/owl-bot-staging/google-cloud-service-management/v1/samples/generated_samples/servicemanagement_v1_generated_service_manager_delete_service_sync.py b/owl-bot-staging/google-cloud-service-management/v1/samples/generated_samples/servicemanagement_v1_generated_service_manager_delete_service_sync.py deleted file mode 100644 index 71e44452852c..000000000000 --- a/owl-bot-staging/google-cloud-service-management/v1/samples/generated_samples/servicemanagement_v1_generated_service_manager_delete_service_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteService -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-service-management - - -# [START servicemanagement_v1_generated_ServiceManager_DeleteService_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 servicemanagement_v1 - - -def sample_delete_service(): - # Create a client - client = servicemanagement_v1.ServiceManagerClient() - - # Initialize request argument(s) - request = servicemanagement_v1.DeleteServiceRequest( - service_name="service_name_value", - ) - - # Make the request - operation = client.delete_service(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END servicemanagement_v1_generated_ServiceManager_DeleteService_sync] diff --git a/owl-bot-staging/google-cloud-service-management/v1/samples/generated_samples/servicemanagement_v1_generated_service_manager_generate_config_report_async.py b/owl-bot-staging/google-cloud-service-management/v1/samples/generated_samples/servicemanagement_v1_generated_service_manager_generate_config_report_async.py deleted file mode 100644 index e3e846c4ac1f..000000000000 --- a/owl-bot-staging/google-cloud-service-management/v1/samples/generated_samples/servicemanagement_v1_generated_service_manager_generate_config_report_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GenerateConfigReport -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-service-management - - -# [START servicemanagement_v1_generated_ServiceManager_GenerateConfigReport_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 servicemanagement_v1 - - -async def sample_generate_config_report(): - # Create a client - client = servicemanagement_v1.ServiceManagerAsyncClient() - - # Initialize request argument(s) - request = servicemanagement_v1.GenerateConfigReportRequest( - ) - - # Make the request - response = await client.generate_config_report(request=request) - - # Handle the response - print(response) - -# [END servicemanagement_v1_generated_ServiceManager_GenerateConfigReport_async] diff --git a/owl-bot-staging/google-cloud-service-management/v1/samples/generated_samples/servicemanagement_v1_generated_service_manager_generate_config_report_sync.py b/owl-bot-staging/google-cloud-service-management/v1/samples/generated_samples/servicemanagement_v1_generated_service_manager_generate_config_report_sync.py deleted file mode 100644 index f0b4255d857e..000000000000 --- a/owl-bot-staging/google-cloud-service-management/v1/samples/generated_samples/servicemanagement_v1_generated_service_manager_generate_config_report_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GenerateConfigReport -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-service-management - - -# [START servicemanagement_v1_generated_ServiceManager_GenerateConfigReport_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 servicemanagement_v1 - - -def sample_generate_config_report(): - # Create a client - client = servicemanagement_v1.ServiceManagerClient() - - # Initialize request argument(s) - request = servicemanagement_v1.GenerateConfigReportRequest( - ) - - # Make the request - response = client.generate_config_report(request=request) - - # Handle the response - print(response) - -# [END servicemanagement_v1_generated_ServiceManager_GenerateConfigReport_sync] diff --git a/owl-bot-staging/google-cloud-service-management/v1/samples/generated_samples/servicemanagement_v1_generated_service_manager_get_service_async.py b/owl-bot-staging/google-cloud-service-management/v1/samples/generated_samples/servicemanagement_v1_generated_service_manager_get_service_async.py deleted file mode 100644 index f7218683f3c1..000000000000 --- a/owl-bot-staging/google-cloud-service-management/v1/samples/generated_samples/servicemanagement_v1_generated_service_manager_get_service_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetService -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-service-management - - -# [START servicemanagement_v1_generated_ServiceManager_GetService_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 servicemanagement_v1 - - -async def sample_get_service(): - # Create a client - client = servicemanagement_v1.ServiceManagerAsyncClient() - - # Initialize request argument(s) - request = servicemanagement_v1.GetServiceRequest( - service_name="service_name_value", - ) - - # Make the request - response = await client.get_service(request=request) - - # Handle the response - print(response) - -# [END servicemanagement_v1_generated_ServiceManager_GetService_async] diff --git a/owl-bot-staging/google-cloud-service-management/v1/samples/generated_samples/servicemanagement_v1_generated_service_manager_get_service_config_async.py b/owl-bot-staging/google-cloud-service-management/v1/samples/generated_samples/servicemanagement_v1_generated_service_manager_get_service_config_async.py deleted file mode 100644 index d4b41e3a771d..000000000000 --- a/owl-bot-staging/google-cloud-service-management/v1/samples/generated_samples/servicemanagement_v1_generated_service_manager_get_service_config_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetServiceConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-service-management - - -# [START servicemanagement_v1_generated_ServiceManager_GetServiceConfig_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 servicemanagement_v1 - - -async def sample_get_service_config(): - # Create a client - client = servicemanagement_v1.ServiceManagerAsyncClient() - - # Initialize request argument(s) - request = servicemanagement_v1.GetServiceConfigRequest( - service_name="service_name_value", - config_id="config_id_value", - ) - - # Make the request - response = await client.get_service_config(request=request) - - # Handle the response - print(response) - -# [END servicemanagement_v1_generated_ServiceManager_GetServiceConfig_async] diff --git a/owl-bot-staging/google-cloud-service-management/v1/samples/generated_samples/servicemanagement_v1_generated_service_manager_get_service_config_sync.py b/owl-bot-staging/google-cloud-service-management/v1/samples/generated_samples/servicemanagement_v1_generated_service_manager_get_service_config_sync.py deleted file mode 100644 index 00b85c938ac9..000000000000 --- a/owl-bot-staging/google-cloud-service-management/v1/samples/generated_samples/servicemanagement_v1_generated_service_manager_get_service_config_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetServiceConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-service-management - - -# [START servicemanagement_v1_generated_ServiceManager_GetServiceConfig_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 servicemanagement_v1 - - -def sample_get_service_config(): - # Create a client - client = servicemanagement_v1.ServiceManagerClient() - - # Initialize request argument(s) - request = servicemanagement_v1.GetServiceConfigRequest( - service_name="service_name_value", - config_id="config_id_value", - ) - - # Make the request - response = client.get_service_config(request=request) - - # Handle the response - print(response) - -# [END servicemanagement_v1_generated_ServiceManager_GetServiceConfig_sync] diff --git a/owl-bot-staging/google-cloud-service-management/v1/samples/generated_samples/servicemanagement_v1_generated_service_manager_get_service_rollout_async.py b/owl-bot-staging/google-cloud-service-management/v1/samples/generated_samples/servicemanagement_v1_generated_service_manager_get_service_rollout_async.py deleted file mode 100644 index b16f66f1f8fe..000000000000 --- a/owl-bot-staging/google-cloud-service-management/v1/samples/generated_samples/servicemanagement_v1_generated_service_manager_get_service_rollout_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetServiceRollout -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-service-management - - -# [START servicemanagement_v1_generated_ServiceManager_GetServiceRollout_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 servicemanagement_v1 - - -async def sample_get_service_rollout(): - # Create a client - client = servicemanagement_v1.ServiceManagerAsyncClient() - - # Initialize request argument(s) - request = servicemanagement_v1.GetServiceRolloutRequest( - service_name="service_name_value", - rollout_id="rollout_id_value", - ) - - # Make the request - response = await client.get_service_rollout(request=request) - - # Handle the response - print(response) - -# [END servicemanagement_v1_generated_ServiceManager_GetServiceRollout_async] diff --git a/owl-bot-staging/google-cloud-service-management/v1/samples/generated_samples/servicemanagement_v1_generated_service_manager_get_service_rollout_sync.py b/owl-bot-staging/google-cloud-service-management/v1/samples/generated_samples/servicemanagement_v1_generated_service_manager_get_service_rollout_sync.py deleted file mode 100644 index 97a265aa9797..000000000000 --- a/owl-bot-staging/google-cloud-service-management/v1/samples/generated_samples/servicemanagement_v1_generated_service_manager_get_service_rollout_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetServiceRollout -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-service-management - - -# [START servicemanagement_v1_generated_ServiceManager_GetServiceRollout_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 servicemanagement_v1 - - -def sample_get_service_rollout(): - # Create a client - client = servicemanagement_v1.ServiceManagerClient() - - # Initialize request argument(s) - request = servicemanagement_v1.GetServiceRolloutRequest( - service_name="service_name_value", - rollout_id="rollout_id_value", - ) - - # Make the request - response = client.get_service_rollout(request=request) - - # Handle the response - print(response) - -# [END servicemanagement_v1_generated_ServiceManager_GetServiceRollout_sync] diff --git a/owl-bot-staging/google-cloud-service-management/v1/samples/generated_samples/servicemanagement_v1_generated_service_manager_get_service_sync.py b/owl-bot-staging/google-cloud-service-management/v1/samples/generated_samples/servicemanagement_v1_generated_service_manager_get_service_sync.py deleted file mode 100644 index 94ad85b447ec..000000000000 --- a/owl-bot-staging/google-cloud-service-management/v1/samples/generated_samples/servicemanagement_v1_generated_service_manager_get_service_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetService -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-service-management - - -# [START servicemanagement_v1_generated_ServiceManager_GetService_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 servicemanagement_v1 - - -def sample_get_service(): - # Create a client - client = servicemanagement_v1.ServiceManagerClient() - - # Initialize request argument(s) - request = servicemanagement_v1.GetServiceRequest( - service_name="service_name_value", - ) - - # Make the request - response = client.get_service(request=request) - - # Handle the response - print(response) - -# [END servicemanagement_v1_generated_ServiceManager_GetService_sync] diff --git a/owl-bot-staging/google-cloud-service-management/v1/samples/generated_samples/servicemanagement_v1_generated_service_manager_list_service_configs_async.py b/owl-bot-staging/google-cloud-service-management/v1/samples/generated_samples/servicemanagement_v1_generated_service_manager_list_service_configs_async.py deleted file mode 100644 index 38e56d2b4bf2..000000000000 --- a/owl-bot-staging/google-cloud-service-management/v1/samples/generated_samples/servicemanagement_v1_generated_service_manager_list_service_configs_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListServiceConfigs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-service-management - - -# [START servicemanagement_v1_generated_ServiceManager_ListServiceConfigs_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 servicemanagement_v1 - - -async def sample_list_service_configs(): - # Create a client - client = servicemanagement_v1.ServiceManagerAsyncClient() - - # Initialize request argument(s) - request = servicemanagement_v1.ListServiceConfigsRequest( - service_name="service_name_value", - ) - - # Make the request - page_result = client.list_service_configs(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END servicemanagement_v1_generated_ServiceManager_ListServiceConfigs_async] diff --git a/owl-bot-staging/google-cloud-service-management/v1/samples/generated_samples/servicemanagement_v1_generated_service_manager_list_service_configs_sync.py b/owl-bot-staging/google-cloud-service-management/v1/samples/generated_samples/servicemanagement_v1_generated_service_manager_list_service_configs_sync.py deleted file mode 100644 index f43de63b4259..000000000000 --- a/owl-bot-staging/google-cloud-service-management/v1/samples/generated_samples/servicemanagement_v1_generated_service_manager_list_service_configs_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListServiceConfigs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-service-management - - -# [START servicemanagement_v1_generated_ServiceManager_ListServiceConfigs_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 servicemanagement_v1 - - -def sample_list_service_configs(): - # Create a client - client = servicemanagement_v1.ServiceManagerClient() - - # Initialize request argument(s) - request = servicemanagement_v1.ListServiceConfigsRequest( - service_name="service_name_value", - ) - - # Make the request - page_result = client.list_service_configs(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END servicemanagement_v1_generated_ServiceManager_ListServiceConfigs_sync] diff --git a/owl-bot-staging/google-cloud-service-management/v1/samples/generated_samples/servicemanagement_v1_generated_service_manager_list_service_rollouts_async.py b/owl-bot-staging/google-cloud-service-management/v1/samples/generated_samples/servicemanagement_v1_generated_service_manager_list_service_rollouts_async.py deleted file mode 100644 index 6054664614eb..000000000000 --- a/owl-bot-staging/google-cloud-service-management/v1/samples/generated_samples/servicemanagement_v1_generated_service_manager_list_service_rollouts_async.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListServiceRollouts -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-service-management - - -# [START servicemanagement_v1_generated_ServiceManager_ListServiceRollouts_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 servicemanagement_v1 - - -async def sample_list_service_rollouts(): - # Create a client - client = servicemanagement_v1.ServiceManagerAsyncClient() - - # Initialize request argument(s) - request = servicemanagement_v1.ListServiceRolloutsRequest( - service_name="service_name_value", - filter="filter_value", - ) - - # Make the request - page_result = client.list_service_rollouts(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END servicemanagement_v1_generated_ServiceManager_ListServiceRollouts_async] diff --git a/owl-bot-staging/google-cloud-service-management/v1/samples/generated_samples/servicemanagement_v1_generated_service_manager_list_service_rollouts_sync.py b/owl-bot-staging/google-cloud-service-management/v1/samples/generated_samples/servicemanagement_v1_generated_service_manager_list_service_rollouts_sync.py deleted file mode 100644 index 214715580014..000000000000 --- a/owl-bot-staging/google-cloud-service-management/v1/samples/generated_samples/servicemanagement_v1_generated_service_manager_list_service_rollouts_sync.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListServiceRollouts -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-service-management - - -# [START servicemanagement_v1_generated_ServiceManager_ListServiceRollouts_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 servicemanagement_v1 - - -def sample_list_service_rollouts(): - # Create a client - client = servicemanagement_v1.ServiceManagerClient() - - # Initialize request argument(s) - request = servicemanagement_v1.ListServiceRolloutsRequest( - service_name="service_name_value", - filter="filter_value", - ) - - # Make the request - page_result = client.list_service_rollouts(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END servicemanagement_v1_generated_ServiceManager_ListServiceRollouts_sync] diff --git a/owl-bot-staging/google-cloud-service-management/v1/samples/generated_samples/servicemanagement_v1_generated_service_manager_list_services_async.py b/owl-bot-staging/google-cloud-service-management/v1/samples/generated_samples/servicemanagement_v1_generated_service_manager_list_services_async.py deleted file mode 100644 index 1c17457c3338..000000000000 --- a/owl-bot-staging/google-cloud-service-management/v1/samples/generated_samples/servicemanagement_v1_generated_service_manager_list_services_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListServices -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-service-management - - -# [START servicemanagement_v1_generated_ServiceManager_ListServices_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 servicemanagement_v1 - - -async def sample_list_services(): - # Create a client - client = servicemanagement_v1.ServiceManagerAsyncClient() - - # Initialize request argument(s) - request = servicemanagement_v1.ListServicesRequest( - ) - - # Make the request - page_result = client.list_services(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END servicemanagement_v1_generated_ServiceManager_ListServices_async] diff --git a/owl-bot-staging/google-cloud-service-management/v1/samples/generated_samples/servicemanagement_v1_generated_service_manager_list_services_sync.py b/owl-bot-staging/google-cloud-service-management/v1/samples/generated_samples/servicemanagement_v1_generated_service_manager_list_services_sync.py deleted file mode 100644 index a9c87f27e194..000000000000 --- a/owl-bot-staging/google-cloud-service-management/v1/samples/generated_samples/servicemanagement_v1_generated_service_manager_list_services_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListServices -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-service-management - - -# [START servicemanagement_v1_generated_ServiceManager_ListServices_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 servicemanagement_v1 - - -def sample_list_services(): - # Create a client - client = servicemanagement_v1.ServiceManagerClient() - - # Initialize request argument(s) - request = servicemanagement_v1.ListServicesRequest( - ) - - # Make the request - page_result = client.list_services(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END servicemanagement_v1_generated_ServiceManager_ListServices_sync] diff --git a/owl-bot-staging/google-cloud-service-management/v1/samples/generated_samples/servicemanagement_v1_generated_service_manager_submit_config_source_async.py b/owl-bot-staging/google-cloud-service-management/v1/samples/generated_samples/servicemanagement_v1_generated_service_manager_submit_config_source_async.py deleted file mode 100644 index 3f8fe02eed7e..000000000000 --- a/owl-bot-staging/google-cloud-service-management/v1/samples/generated_samples/servicemanagement_v1_generated_service_manager_submit_config_source_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SubmitConfigSource -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-service-management - - -# [START servicemanagement_v1_generated_ServiceManager_SubmitConfigSource_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 servicemanagement_v1 - - -async def sample_submit_config_source(): - # Create a client - client = servicemanagement_v1.ServiceManagerAsyncClient() - - # Initialize request argument(s) - request = servicemanagement_v1.SubmitConfigSourceRequest( - service_name="service_name_value", - ) - - # Make the request - operation = client.submit_config_source(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END servicemanagement_v1_generated_ServiceManager_SubmitConfigSource_async] diff --git a/owl-bot-staging/google-cloud-service-management/v1/samples/generated_samples/servicemanagement_v1_generated_service_manager_submit_config_source_sync.py b/owl-bot-staging/google-cloud-service-management/v1/samples/generated_samples/servicemanagement_v1_generated_service_manager_submit_config_source_sync.py deleted file mode 100644 index 96a61ef93c6d..000000000000 --- a/owl-bot-staging/google-cloud-service-management/v1/samples/generated_samples/servicemanagement_v1_generated_service_manager_submit_config_source_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SubmitConfigSource -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-service-management - - -# [START servicemanagement_v1_generated_ServiceManager_SubmitConfigSource_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 servicemanagement_v1 - - -def sample_submit_config_source(): - # Create a client - client = servicemanagement_v1.ServiceManagerClient() - - # Initialize request argument(s) - request = servicemanagement_v1.SubmitConfigSourceRequest( - service_name="service_name_value", - ) - - # Make the request - operation = client.submit_config_source(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END servicemanagement_v1_generated_ServiceManager_SubmitConfigSource_sync] diff --git a/owl-bot-staging/google-cloud-service-management/v1/samples/generated_samples/servicemanagement_v1_generated_service_manager_undelete_service_async.py b/owl-bot-staging/google-cloud-service-management/v1/samples/generated_samples/servicemanagement_v1_generated_service_manager_undelete_service_async.py deleted file mode 100644 index ec9010ce7767..000000000000 --- a/owl-bot-staging/google-cloud-service-management/v1/samples/generated_samples/servicemanagement_v1_generated_service_manager_undelete_service_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UndeleteService -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-service-management - - -# [START servicemanagement_v1_generated_ServiceManager_UndeleteService_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 servicemanagement_v1 - - -async def sample_undelete_service(): - # Create a client - client = servicemanagement_v1.ServiceManagerAsyncClient() - - # Initialize request argument(s) - request = servicemanagement_v1.UndeleteServiceRequest( - service_name="service_name_value", - ) - - # Make the request - operation = client.undelete_service(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END servicemanagement_v1_generated_ServiceManager_UndeleteService_async] diff --git a/owl-bot-staging/google-cloud-service-management/v1/samples/generated_samples/servicemanagement_v1_generated_service_manager_undelete_service_sync.py b/owl-bot-staging/google-cloud-service-management/v1/samples/generated_samples/servicemanagement_v1_generated_service_manager_undelete_service_sync.py deleted file mode 100644 index 6e3f000fb8cc..000000000000 --- a/owl-bot-staging/google-cloud-service-management/v1/samples/generated_samples/servicemanagement_v1_generated_service_manager_undelete_service_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UndeleteService -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-service-management - - -# [START servicemanagement_v1_generated_ServiceManager_UndeleteService_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 servicemanagement_v1 - - -def sample_undelete_service(): - # Create a client - client = servicemanagement_v1.ServiceManagerClient() - - # Initialize request argument(s) - request = servicemanagement_v1.UndeleteServiceRequest( - service_name="service_name_value", - ) - - # Make the request - operation = client.undelete_service(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END servicemanagement_v1_generated_ServiceManager_UndeleteService_sync] diff --git a/owl-bot-staging/google-cloud-service-management/v1/samples/generated_samples/snippet_metadata_google.api.servicemanagement.v1.json b/owl-bot-staging/google-cloud-service-management/v1/samples/generated_samples/snippet_metadata_google.api.servicemanagement.v1.json deleted file mode 100644 index fb37827cecec..000000000000 --- a/owl-bot-staging/google-cloud-service-management/v1/samples/generated_samples/snippet_metadata_google.api.servicemanagement.v1.json +++ /dev/null @@ -1,2188 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.api.servicemanagement.v1", - "version": "v1" - } - ], - "language": "PYTHON", - "name": "google-cloud-service-management", - "version": "0.1.0" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.servicemanagement_v1.ServiceManagerAsyncClient", - "shortName": "ServiceManagerAsyncClient" - }, - "fullName": "google.cloud.servicemanagement_v1.ServiceManagerAsyncClient.create_service_config", - "method": { - "fullName": "google.api.servicemanagement.v1.ServiceManager.CreateServiceConfig", - "service": { - "fullName": "google.api.servicemanagement.v1.ServiceManager", - "shortName": "ServiceManager" - }, - "shortName": "CreateServiceConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.servicemanagement_v1.types.CreateServiceConfigRequest" - }, - { - "name": "service_name", - "type": "str" - }, - { - "name": "service_config", - "type": "google.api.service_pb2.Service" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api.service_pb2.Service", - "shortName": "create_service_config" - }, - "description": "Sample for CreateServiceConfig", - "file": "servicemanagement_v1_generated_service_manager_create_service_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "servicemanagement_v1_generated_ServiceManager_CreateServiceConfig_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": "servicemanagement_v1_generated_service_manager_create_service_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.servicemanagement_v1.ServiceManagerClient", - "shortName": "ServiceManagerClient" - }, - "fullName": "google.cloud.servicemanagement_v1.ServiceManagerClient.create_service_config", - "method": { - "fullName": "google.api.servicemanagement.v1.ServiceManager.CreateServiceConfig", - "service": { - "fullName": "google.api.servicemanagement.v1.ServiceManager", - "shortName": "ServiceManager" - }, - "shortName": "CreateServiceConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.servicemanagement_v1.types.CreateServiceConfigRequest" - }, - { - "name": "service_name", - "type": "str" - }, - { - "name": "service_config", - "type": "google.api.service_pb2.Service" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api.service_pb2.Service", - "shortName": "create_service_config" - }, - "description": "Sample for CreateServiceConfig", - "file": "servicemanagement_v1_generated_service_manager_create_service_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "servicemanagement_v1_generated_ServiceManager_CreateServiceConfig_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": "servicemanagement_v1_generated_service_manager_create_service_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.servicemanagement_v1.ServiceManagerAsyncClient", - "shortName": "ServiceManagerAsyncClient" - }, - "fullName": "google.cloud.servicemanagement_v1.ServiceManagerAsyncClient.create_service_rollout", - "method": { - "fullName": "google.api.servicemanagement.v1.ServiceManager.CreateServiceRollout", - "service": { - "fullName": "google.api.servicemanagement.v1.ServiceManager", - "shortName": "ServiceManager" - }, - "shortName": "CreateServiceRollout" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.servicemanagement_v1.types.CreateServiceRolloutRequest" - }, - { - "name": "service_name", - "type": "str" - }, - { - "name": "rollout", - "type": "google.cloud.servicemanagement_v1.types.Rollout" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_service_rollout" - }, - "description": "Sample for CreateServiceRollout", - "file": "servicemanagement_v1_generated_service_manager_create_service_rollout_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "servicemanagement_v1_generated_ServiceManager_CreateServiceRollout_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": "servicemanagement_v1_generated_service_manager_create_service_rollout_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.servicemanagement_v1.ServiceManagerClient", - "shortName": "ServiceManagerClient" - }, - "fullName": "google.cloud.servicemanagement_v1.ServiceManagerClient.create_service_rollout", - "method": { - "fullName": "google.api.servicemanagement.v1.ServiceManager.CreateServiceRollout", - "service": { - "fullName": "google.api.servicemanagement.v1.ServiceManager", - "shortName": "ServiceManager" - }, - "shortName": "CreateServiceRollout" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.servicemanagement_v1.types.CreateServiceRolloutRequest" - }, - { - "name": "service_name", - "type": "str" - }, - { - "name": "rollout", - "type": "google.cloud.servicemanagement_v1.types.Rollout" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "create_service_rollout" - }, - "description": "Sample for CreateServiceRollout", - "file": "servicemanagement_v1_generated_service_manager_create_service_rollout_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "servicemanagement_v1_generated_ServiceManager_CreateServiceRollout_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": "servicemanagement_v1_generated_service_manager_create_service_rollout_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.servicemanagement_v1.ServiceManagerAsyncClient", - "shortName": "ServiceManagerAsyncClient" - }, - "fullName": "google.cloud.servicemanagement_v1.ServiceManagerAsyncClient.create_service", - "method": { - "fullName": "google.api.servicemanagement.v1.ServiceManager.CreateService", - "service": { - "fullName": "google.api.servicemanagement.v1.ServiceManager", - "shortName": "ServiceManager" - }, - "shortName": "CreateService" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.servicemanagement_v1.types.CreateServiceRequest" - }, - { - "name": "service", - "type": "google.cloud.servicemanagement_v1.types.ManagedService" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_service" - }, - "description": "Sample for CreateService", - "file": "servicemanagement_v1_generated_service_manager_create_service_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "servicemanagement_v1_generated_ServiceManager_CreateService_async", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "servicemanagement_v1_generated_service_manager_create_service_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.servicemanagement_v1.ServiceManagerClient", - "shortName": "ServiceManagerClient" - }, - "fullName": "google.cloud.servicemanagement_v1.ServiceManagerClient.create_service", - "method": { - "fullName": "google.api.servicemanagement.v1.ServiceManager.CreateService", - "service": { - "fullName": "google.api.servicemanagement.v1.ServiceManager", - "shortName": "ServiceManager" - }, - "shortName": "CreateService" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.servicemanagement_v1.types.CreateServiceRequest" - }, - { - "name": "service", - "type": "google.cloud.servicemanagement_v1.types.ManagedService" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "create_service" - }, - "description": "Sample for CreateService", - "file": "servicemanagement_v1_generated_service_manager_create_service_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "servicemanagement_v1_generated_ServiceManager_CreateService_sync", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "servicemanagement_v1_generated_service_manager_create_service_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.servicemanagement_v1.ServiceManagerAsyncClient", - "shortName": "ServiceManagerAsyncClient" - }, - "fullName": "google.cloud.servicemanagement_v1.ServiceManagerAsyncClient.delete_service", - "method": { - "fullName": "google.api.servicemanagement.v1.ServiceManager.DeleteService", - "service": { - "fullName": "google.api.servicemanagement.v1.ServiceManager", - "shortName": "ServiceManager" - }, - "shortName": "DeleteService" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.servicemanagement_v1.types.DeleteServiceRequest" - }, - { - "name": "service_name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_service" - }, - "description": "Sample for DeleteService", - "file": "servicemanagement_v1_generated_service_manager_delete_service_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "servicemanagement_v1_generated_ServiceManager_DeleteService_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": "servicemanagement_v1_generated_service_manager_delete_service_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.servicemanagement_v1.ServiceManagerClient", - "shortName": "ServiceManagerClient" - }, - "fullName": "google.cloud.servicemanagement_v1.ServiceManagerClient.delete_service", - "method": { - "fullName": "google.api.servicemanagement.v1.ServiceManager.DeleteService", - "service": { - "fullName": "google.api.servicemanagement.v1.ServiceManager", - "shortName": "ServiceManager" - }, - "shortName": "DeleteService" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.servicemanagement_v1.types.DeleteServiceRequest" - }, - { - "name": "service_name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "delete_service" - }, - "description": "Sample for DeleteService", - "file": "servicemanagement_v1_generated_service_manager_delete_service_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "servicemanagement_v1_generated_ServiceManager_DeleteService_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": "servicemanagement_v1_generated_service_manager_delete_service_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.servicemanagement_v1.ServiceManagerAsyncClient", - "shortName": "ServiceManagerAsyncClient" - }, - "fullName": "google.cloud.servicemanagement_v1.ServiceManagerAsyncClient.generate_config_report", - "method": { - "fullName": "google.api.servicemanagement.v1.ServiceManager.GenerateConfigReport", - "service": { - "fullName": "google.api.servicemanagement.v1.ServiceManager", - "shortName": "ServiceManager" - }, - "shortName": "GenerateConfigReport" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.servicemanagement_v1.types.GenerateConfigReportRequest" - }, - { - "name": "new_config", - "type": "google.protobuf.any_pb2.Any" - }, - { - "name": "old_config", - "type": "google.protobuf.any_pb2.Any" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.servicemanagement_v1.types.GenerateConfigReportResponse", - "shortName": "generate_config_report" - }, - "description": "Sample for GenerateConfigReport", - "file": "servicemanagement_v1_generated_service_manager_generate_config_report_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "servicemanagement_v1_generated_ServiceManager_GenerateConfigReport_async", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "servicemanagement_v1_generated_service_manager_generate_config_report_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.servicemanagement_v1.ServiceManagerClient", - "shortName": "ServiceManagerClient" - }, - "fullName": "google.cloud.servicemanagement_v1.ServiceManagerClient.generate_config_report", - "method": { - "fullName": "google.api.servicemanagement.v1.ServiceManager.GenerateConfigReport", - "service": { - "fullName": "google.api.servicemanagement.v1.ServiceManager", - "shortName": "ServiceManager" - }, - "shortName": "GenerateConfigReport" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.servicemanagement_v1.types.GenerateConfigReportRequest" - }, - { - "name": "new_config", - "type": "google.protobuf.any_pb2.Any" - }, - { - "name": "old_config", - "type": "google.protobuf.any_pb2.Any" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.servicemanagement_v1.types.GenerateConfigReportResponse", - "shortName": "generate_config_report" - }, - "description": "Sample for GenerateConfigReport", - "file": "servicemanagement_v1_generated_service_manager_generate_config_report_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "servicemanagement_v1_generated_ServiceManager_GenerateConfigReport_sync", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "servicemanagement_v1_generated_service_manager_generate_config_report_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.servicemanagement_v1.ServiceManagerAsyncClient", - "shortName": "ServiceManagerAsyncClient" - }, - "fullName": "google.cloud.servicemanagement_v1.ServiceManagerAsyncClient.get_service_config", - "method": { - "fullName": "google.api.servicemanagement.v1.ServiceManager.GetServiceConfig", - "service": { - "fullName": "google.api.servicemanagement.v1.ServiceManager", - "shortName": "ServiceManager" - }, - "shortName": "GetServiceConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.servicemanagement_v1.types.GetServiceConfigRequest" - }, - { - "name": "service_name", - "type": "str" - }, - { - "name": "config_id", - "type": "str" - }, - { - "name": "view", - "type": "google.cloud.servicemanagement_v1.types.GetServiceConfigRequest.ConfigView" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api.service_pb2.Service", - "shortName": "get_service_config" - }, - "description": "Sample for GetServiceConfig", - "file": "servicemanagement_v1_generated_service_manager_get_service_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "servicemanagement_v1_generated_ServiceManager_GetServiceConfig_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": "servicemanagement_v1_generated_service_manager_get_service_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.servicemanagement_v1.ServiceManagerClient", - "shortName": "ServiceManagerClient" - }, - "fullName": "google.cloud.servicemanagement_v1.ServiceManagerClient.get_service_config", - "method": { - "fullName": "google.api.servicemanagement.v1.ServiceManager.GetServiceConfig", - "service": { - "fullName": "google.api.servicemanagement.v1.ServiceManager", - "shortName": "ServiceManager" - }, - "shortName": "GetServiceConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.servicemanagement_v1.types.GetServiceConfigRequest" - }, - { - "name": "service_name", - "type": "str" - }, - { - "name": "config_id", - "type": "str" - }, - { - "name": "view", - "type": "google.cloud.servicemanagement_v1.types.GetServiceConfigRequest.ConfigView" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api.service_pb2.Service", - "shortName": "get_service_config" - }, - "description": "Sample for GetServiceConfig", - "file": "servicemanagement_v1_generated_service_manager_get_service_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "servicemanagement_v1_generated_ServiceManager_GetServiceConfig_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": "servicemanagement_v1_generated_service_manager_get_service_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.servicemanagement_v1.ServiceManagerAsyncClient", - "shortName": "ServiceManagerAsyncClient" - }, - "fullName": "google.cloud.servicemanagement_v1.ServiceManagerAsyncClient.get_service_rollout", - "method": { - "fullName": "google.api.servicemanagement.v1.ServiceManager.GetServiceRollout", - "service": { - "fullName": "google.api.servicemanagement.v1.ServiceManager", - "shortName": "ServiceManager" - }, - "shortName": "GetServiceRollout" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.servicemanagement_v1.types.GetServiceRolloutRequest" - }, - { - "name": "service_name", - "type": "str" - }, - { - "name": "rollout_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.servicemanagement_v1.types.Rollout", - "shortName": "get_service_rollout" - }, - "description": "Sample for GetServiceRollout", - "file": "servicemanagement_v1_generated_service_manager_get_service_rollout_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "servicemanagement_v1_generated_ServiceManager_GetServiceRollout_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": "servicemanagement_v1_generated_service_manager_get_service_rollout_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.servicemanagement_v1.ServiceManagerClient", - "shortName": "ServiceManagerClient" - }, - "fullName": "google.cloud.servicemanagement_v1.ServiceManagerClient.get_service_rollout", - "method": { - "fullName": "google.api.servicemanagement.v1.ServiceManager.GetServiceRollout", - "service": { - "fullName": "google.api.servicemanagement.v1.ServiceManager", - "shortName": "ServiceManager" - }, - "shortName": "GetServiceRollout" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.servicemanagement_v1.types.GetServiceRolloutRequest" - }, - { - "name": "service_name", - "type": "str" - }, - { - "name": "rollout_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.servicemanagement_v1.types.Rollout", - "shortName": "get_service_rollout" - }, - "description": "Sample for GetServiceRollout", - "file": "servicemanagement_v1_generated_service_manager_get_service_rollout_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "servicemanagement_v1_generated_ServiceManager_GetServiceRollout_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": "servicemanagement_v1_generated_service_manager_get_service_rollout_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.servicemanagement_v1.ServiceManagerAsyncClient", - "shortName": "ServiceManagerAsyncClient" - }, - "fullName": "google.cloud.servicemanagement_v1.ServiceManagerAsyncClient.get_service", - "method": { - "fullName": "google.api.servicemanagement.v1.ServiceManager.GetService", - "service": { - "fullName": "google.api.servicemanagement.v1.ServiceManager", - "shortName": "ServiceManager" - }, - "shortName": "GetService" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.servicemanagement_v1.types.GetServiceRequest" - }, - { - "name": "service_name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.servicemanagement_v1.types.ManagedService", - "shortName": "get_service" - }, - "description": "Sample for GetService", - "file": "servicemanagement_v1_generated_service_manager_get_service_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "servicemanagement_v1_generated_ServiceManager_GetService_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": "servicemanagement_v1_generated_service_manager_get_service_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.servicemanagement_v1.ServiceManagerClient", - "shortName": "ServiceManagerClient" - }, - "fullName": "google.cloud.servicemanagement_v1.ServiceManagerClient.get_service", - "method": { - "fullName": "google.api.servicemanagement.v1.ServiceManager.GetService", - "service": { - "fullName": "google.api.servicemanagement.v1.ServiceManager", - "shortName": "ServiceManager" - }, - "shortName": "GetService" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.servicemanagement_v1.types.GetServiceRequest" - }, - { - "name": "service_name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.servicemanagement_v1.types.ManagedService", - "shortName": "get_service" - }, - "description": "Sample for GetService", - "file": "servicemanagement_v1_generated_service_manager_get_service_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "servicemanagement_v1_generated_ServiceManager_GetService_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": "servicemanagement_v1_generated_service_manager_get_service_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.servicemanagement_v1.ServiceManagerAsyncClient", - "shortName": "ServiceManagerAsyncClient" - }, - "fullName": "google.cloud.servicemanagement_v1.ServiceManagerAsyncClient.list_service_configs", - "method": { - "fullName": "google.api.servicemanagement.v1.ServiceManager.ListServiceConfigs", - "service": { - "fullName": "google.api.servicemanagement.v1.ServiceManager", - "shortName": "ServiceManager" - }, - "shortName": "ListServiceConfigs" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.servicemanagement_v1.types.ListServiceConfigsRequest" - }, - { - "name": "service_name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.servicemanagement_v1.services.service_manager.pagers.ListServiceConfigsAsyncPager", - "shortName": "list_service_configs" - }, - "description": "Sample for ListServiceConfigs", - "file": "servicemanagement_v1_generated_service_manager_list_service_configs_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "servicemanagement_v1_generated_ServiceManager_ListServiceConfigs_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": "servicemanagement_v1_generated_service_manager_list_service_configs_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.servicemanagement_v1.ServiceManagerClient", - "shortName": "ServiceManagerClient" - }, - "fullName": "google.cloud.servicemanagement_v1.ServiceManagerClient.list_service_configs", - "method": { - "fullName": "google.api.servicemanagement.v1.ServiceManager.ListServiceConfigs", - "service": { - "fullName": "google.api.servicemanagement.v1.ServiceManager", - "shortName": "ServiceManager" - }, - "shortName": "ListServiceConfigs" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.servicemanagement_v1.types.ListServiceConfigsRequest" - }, - { - "name": "service_name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.servicemanagement_v1.services.service_manager.pagers.ListServiceConfigsPager", - "shortName": "list_service_configs" - }, - "description": "Sample for ListServiceConfigs", - "file": "servicemanagement_v1_generated_service_manager_list_service_configs_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "servicemanagement_v1_generated_ServiceManager_ListServiceConfigs_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": "servicemanagement_v1_generated_service_manager_list_service_configs_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.servicemanagement_v1.ServiceManagerAsyncClient", - "shortName": "ServiceManagerAsyncClient" - }, - "fullName": "google.cloud.servicemanagement_v1.ServiceManagerAsyncClient.list_service_rollouts", - "method": { - "fullName": "google.api.servicemanagement.v1.ServiceManager.ListServiceRollouts", - "service": { - "fullName": "google.api.servicemanagement.v1.ServiceManager", - "shortName": "ServiceManager" - }, - "shortName": "ListServiceRollouts" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.servicemanagement_v1.types.ListServiceRolloutsRequest" - }, - { - "name": "service_name", - "type": "str" - }, - { - "name": "filter", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.servicemanagement_v1.services.service_manager.pagers.ListServiceRolloutsAsyncPager", - "shortName": "list_service_rollouts" - }, - "description": "Sample for ListServiceRollouts", - "file": "servicemanagement_v1_generated_service_manager_list_service_rollouts_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "servicemanagement_v1_generated_ServiceManager_ListServiceRollouts_async", - "segments": [ - { - "end": 53, - "start": 27, - "type": "FULL" - }, - { - "end": 53, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 54, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "servicemanagement_v1_generated_service_manager_list_service_rollouts_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.servicemanagement_v1.ServiceManagerClient", - "shortName": "ServiceManagerClient" - }, - "fullName": "google.cloud.servicemanagement_v1.ServiceManagerClient.list_service_rollouts", - "method": { - "fullName": "google.api.servicemanagement.v1.ServiceManager.ListServiceRollouts", - "service": { - "fullName": "google.api.servicemanagement.v1.ServiceManager", - "shortName": "ServiceManager" - }, - "shortName": "ListServiceRollouts" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.servicemanagement_v1.types.ListServiceRolloutsRequest" - }, - { - "name": "service_name", - "type": "str" - }, - { - "name": "filter", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.servicemanagement_v1.services.service_manager.pagers.ListServiceRolloutsPager", - "shortName": "list_service_rollouts" - }, - "description": "Sample for ListServiceRollouts", - "file": "servicemanagement_v1_generated_service_manager_list_service_rollouts_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "servicemanagement_v1_generated_ServiceManager_ListServiceRollouts_sync", - "segments": [ - { - "end": 53, - "start": 27, - "type": "FULL" - }, - { - "end": 53, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 54, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "servicemanagement_v1_generated_service_manager_list_service_rollouts_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.servicemanagement_v1.ServiceManagerAsyncClient", - "shortName": "ServiceManagerAsyncClient" - }, - "fullName": "google.cloud.servicemanagement_v1.ServiceManagerAsyncClient.list_services", - "method": { - "fullName": "google.api.servicemanagement.v1.ServiceManager.ListServices", - "service": { - "fullName": "google.api.servicemanagement.v1.ServiceManager", - "shortName": "ServiceManager" - }, - "shortName": "ListServices" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.servicemanagement_v1.types.ListServicesRequest" - }, - { - "name": "producer_project_id", - "type": "str" - }, - { - "name": "consumer_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.servicemanagement_v1.services.service_manager.pagers.ListServicesAsyncPager", - "shortName": "list_services" - }, - "description": "Sample for ListServices", - "file": "servicemanagement_v1_generated_service_manager_list_services_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "servicemanagement_v1_generated_ServiceManager_ListServices_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "servicemanagement_v1_generated_service_manager_list_services_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.servicemanagement_v1.ServiceManagerClient", - "shortName": "ServiceManagerClient" - }, - "fullName": "google.cloud.servicemanagement_v1.ServiceManagerClient.list_services", - "method": { - "fullName": "google.api.servicemanagement.v1.ServiceManager.ListServices", - "service": { - "fullName": "google.api.servicemanagement.v1.ServiceManager", - "shortName": "ServiceManager" - }, - "shortName": "ListServices" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.servicemanagement_v1.types.ListServicesRequest" - }, - { - "name": "producer_project_id", - "type": "str" - }, - { - "name": "consumer_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.servicemanagement_v1.services.service_manager.pagers.ListServicesPager", - "shortName": "list_services" - }, - "description": "Sample for ListServices", - "file": "servicemanagement_v1_generated_service_manager_list_services_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "servicemanagement_v1_generated_ServiceManager_ListServices_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "servicemanagement_v1_generated_service_manager_list_services_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.servicemanagement_v1.ServiceManagerAsyncClient", - "shortName": "ServiceManagerAsyncClient" - }, - "fullName": "google.cloud.servicemanagement_v1.ServiceManagerAsyncClient.submit_config_source", - "method": { - "fullName": "google.api.servicemanagement.v1.ServiceManager.SubmitConfigSource", - "service": { - "fullName": "google.api.servicemanagement.v1.ServiceManager", - "shortName": "ServiceManager" - }, - "shortName": "SubmitConfigSource" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.servicemanagement_v1.types.SubmitConfigSourceRequest" - }, - { - "name": "service_name", - "type": "str" - }, - { - "name": "config_source", - "type": "google.cloud.servicemanagement_v1.types.ConfigSource" - }, - { - "name": "validate_only", - "type": "bool" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "submit_config_source" - }, - "description": "Sample for SubmitConfigSource", - "file": "servicemanagement_v1_generated_service_manager_submit_config_source_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "servicemanagement_v1_generated_ServiceManager_SubmitConfigSource_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": "servicemanagement_v1_generated_service_manager_submit_config_source_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.servicemanagement_v1.ServiceManagerClient", - "shortName": "ServiceManagerClient" - }, - "fullName": "google.cloud.servicemanagement_v1.ServiceManagerClient.submit_config_source", - "method": { - "fullName": "google.api.servicemanagement.v1.ServiceManager.SubmitConfigSource", - "service": { - "fullName": "google.api.servicemanagement.v1.ServiceManager", - "shortName": "ServiceManager" - }, - "shortName": "SubmitConfigSource" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.servicemanagement_v1.types.SubmitConfigSourceRequest" - }, - { - "name": "service_name", - "type": "str" - }, - { - "name": "config_source", - "type": "google.cloud.servicemanagement_v1.types.ConfigSource" - }, - { - "name": "validate_only", - "type": "bool" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "submit_config_source" - }, - "description": "Sample for SubmitConfigSource", - "file": "servicemanagement_v1_generated_service_manager_submit_config_source_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "servicemanagement_v1_generated_ServiceManager_SubmitConfigSource_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": "servicemanagement_v1_generated_service_manager_submit_config_source_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.servicemanagement_v1.ServiceManagerAsyncClient", - "shortName": "ServiceManagerAsyncClient" - }, - "fullName": "google.cloud.servicemanagement_v1.ServiceManagerAsyncClient.undelete_service", - "method": { - "fullName": "google.api.servicemanagement.v1.ServiceManager.UndeleteService", - "service": { - "fullName": "google.api.servicemanagement.v1.ServiceManager", - "shortName": "ServiceManager" - }, - "shortName": "UndeleteService" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.servicemanagement_v1.types.UndeleteServiceRequest" - }, - { - "name": "service_name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "undelete_service" - }, - "description": "Sample for UndeleteService", - "file": "servicemanagement_v1_generated_service_manager_undelete_service_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "servicemanagement_v1_generated_ServiceManager_UndeleteService_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": "servicemanagement_v1_generated_service_manager_undelete_service_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.servicemanagement_v1.ServiceManagerClient", - "shortName": "ServiceManagerClient" - }, - "fullName": "google.cloud.servicemanagement_v1.ServiceManagerClient.undelete_service", - "method": { - "fullName": "google.api.servicemanagement.v1.ServiceManager.UndeleteService", - "service": { - "fullName": "google.api.servicemanagement.v1.ServiceManager", - "shortName": "ServiceManager" - }, - "shortName": "UndeleteService" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.servicemanagement_v1.types.UndeleteServiceRequest" - }, - { - "name": "service_name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "undelete_service" - }, - "description": "Sample for UndeleteService", - "file": "servicemanagement_v1_generated_service_manager_undelete_service_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "servicemanagement_v1_generated_ServiceManager_UndeleteService_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": "servicemanagement_v1_generated_service_manager_undelete_service_sync.py" - } - ] -} diff --git a/owl-bot-staging/google-cloud-service-management/v1/scripts/fixup_servicemanagement_v1_keywords.py b/owl-bot-staging/google-cloud-service-management/v1/scripts/fixup_servicemanagement_v1_keywords.py deleted file mode 100644 index 319d760b1b39..000000000000 --- a/owl-bot-staging/google-cloud-service-management/v1/scripts/fixup_servicemanagement_v1_keywords.py +++ /dev/null @@ -1,188 +0,0 @@ -#! /usr/bin/env python3 -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 servicemanagementCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'create_service': ('service', ), - 'create_service_config': ('service_name', 'service_config', ), - 'create_service_rollout': ('service_name', 'rollout', ), - 'delete_service': ('service_name', ), - 'generate_config_report': ('new_config', 'old_config', ), - 'get_service': ('service_name', ), - 'get_service_config': ('service_name', 'config_id', 'view', ), - 'get_service_rollout': ('service_name', 'rollout_id', ), - 'list_service_configs': ('service_name', 'page_token', 'page_size', ), - 'list_service_rollouts': ('service_name', 'filter', 'page_token', 'page_size', ), - 'list_services': ('producer_project_id', 'page_size', 'page_token', 'consumer_id', ), - 'submit_config_source': ('service_name', 'config_source', 'validate_only', ), - 'undelete_service': ('service_name', ), - } - - 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=servicemanagementCallTransformer(), -): - """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 servicemanagement 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-service-management/v1/setup.py b/owl-bot-staging/google-cloud-service-management/v1/setup.py deleted file mode 100644 index a1a6aff87821..000000000000 --- a/owl-bot-staging/google-cloud-service-management/v1/setup.py +++ /dev/null @@ -1,99 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-service-management' - - -description = "Google Cloud Service Management API client library" - -version = None - -with open(os.path.join(package_root, 'google/cloud/servicemanagement/gapic_version.py')) as fp: - version_candidates = re.findall(r"(?<=\")\d+.\d+.\d+(?=\")", fp.read()) - assert (len(version_candidates) == 1) - version = version_candidates[0] - -if version[0] == "0": - release_status = "Development Status :: 4 - Beta" -else: - release_status = "Development Status :: 5 - Production/Stable" - -dependencies = [ - "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - # Exclude incompatible versions of `google-auth` - # See https://github.com/googleapis/google-cloud-python/issues/12364 - "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", - "proto-plus >= 1.22.3, <2.0.0dev", - "proto-plus >= 1.25.0, <2.0.0dev; python_version >= '3.13'", - "protobuf>=3.20.2,<6.0.0dev,!=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", -] -extras = { -} -url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-service-management" - -package_root = os.path.abspath(os.path.dirname(__file__)) - -readme_filename = os.path.join(package_root, "README.rst") -with io.open(readme_filename, encoding="utf-8") as readme_file: - readme = readme_file.read() - -packages = [ - package - for package in setuptools.find_namespace_packages() - if package.startswith("google") -] - -setuptools.setup( - name=name, - version=version, - description=description, - long_description=readme, - author="Google LLC", - author_email="googleapis-packages@google.com", - license="Apache 2.0", - url=url, - classifiers=[ - release_status, - "Intended Audience :: Developers", - "License :: OSI Approved :: Apache Software License", - "Programming Language :: Python", - "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.7", - "Programming Language :: Python :: 3.8", - "Programming Language :: Python :: 3.9", - "Programming Language :: Python :: 3.10", - "Programming Language :: Python :: 3.11", - "Programming Language :: Python :: 3.12", - "Programming Language :: Python :: 3.13", - "Operating System :: OS Independent", - "Topic :: Internet", - ], - platforms="Posix; MacOS X; Windows", - packages=packages, - python_requires=">=3.7", - install_requires=dependencies, - extras_require=extras, - include_package_data=True, - zip_safe=False, -) diff --git a/owl-bot-staging/google-cloud-service-management/v1/testing/constraints-3.10.txt b/owl-bot-staging/google-cloud-service-management/v1/testing/constraints-3.10.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-service-management/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-service-management/v1/testing/constraints-3.11.txt b/owl-bot-staging/google-cloud-service-management/v1/testing/constraints-3.11.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-service-management/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-service-management/v1/testing/constraints-3.12.txt b/owl-bot-staging/google-cloud-service-management/v1/testing/constraints-3.12.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-service-management/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-service-management/v1/testing/constraints-3.13.txt b/owl-bot-staging/google-cloud-service-management/v1/testing/constraints-3.13.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-service-management/v1/testing/constraints-3.13.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-service-management/v1/testing/constraints-3.7.txt b/owl-bot-staging/google-cloud-service-management/v1/testing/constraints-3.7.txt deleted file mode 100644 index a81fb6bcd05c..000000000000 --- a/owl-bot-staging/google-cloud-service-management/v1/testing/constraints-3.7.txt +++ /dev/null @@ -1,11 +0,0 @@ -# This constraints file is used to check that lower bounds -# are correct in setup.py -# List all library dependencies and extras in this file. -# Pin the version to the lower bound. -# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0dev", -# Then this file should have google-cloud-foo==1.14.0 -google-api-core==1.34.1 -google-auth==2.14.1 -proto-plus==1.22.3 -protobuf==3.20.2 -grpc-google-iam-v1==0.12.4 diff --git a/owl-bot-staging/google-cloud-service-management/v1/testing/constraints-3.8.txt b/owl-bot-staging/google-cloud-service-management/v1/testing/constraints-3.8.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-service-management/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-service-management/v1/testing/constraints-3.9.txt b/owl-bot-staging/google-cloud-service-management/v1/testing/constraints-3.9.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-service-management/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-service-management/v1/tests/__init__.py b/owl-bot-staging/google-cloud-service-management/v1/tests/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-service-management/v1/tests/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-service-management/v1/tests/unit/__init__.py b/owl-bot-staging/google-cloud-service-management/v1/tests/unit/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-service-management/v1/tests/unit/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-service-management/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/google-cloud-service-management/v1/tests/unit/gapic/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-service-management/v1/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-service-management/v1/tests/unit/gapic/servicemanagement_v1/__init__.py b/owl-bot-staging/google-cloud-service-management/v1/tests/unit/gapic/servicemanagement_v1/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-service-management/v1/tests/unit/gapic/servicemanagement_v1/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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-service-management/v1/tests/unit/gapic/servicemanagement_v1/test_service_manager.py b/owl-bot-staging/google-cloud-service-management/v1/tests/unit/gapic/servicemanagement_v1/test_service_manager.py deleted file mode 100644 index 80c4b0d9548c..000000000000 --- a/owl-bot-staging/google-cloud-service-management/v1/tests/unit/gapic/servicemanagement_v1/test_service_manager.py +++ /dev/null @@ -1,11755 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable, AsyncIterable -from google.protobuf import json_format -import json -import math -import pytest -from google.api_core import api_core_version -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -try: - from google.auth.aio import credentials as ga_credentials_async - HAS_GOOGLE_AUTH_AIO = True -except ImportError: # pragma: NO COVER - HAS_GOOGLE_AUTH_AIO = False - -from google.api import auth_pb2 # type: ignore -from google.api import backend_pb2 # type: ignore -from google.api import billing_pb2 # type: ignore -from google.api import client_pb2 # type: ignore -from google.api import context_pb2 # type: ignore -from google.api import control_pb2 # type: ignore -from google.api import documentation_pb2 # type: ignore -from google.api import endpoint_pb2 # type: ignore -from google.api import http_pb2 # type: ignore -from google.api import label_pb2 # type: ignore -from google.api import launch_stage_pb2 # type: ignore -from google.api import log_pb2 # type: ignore -from google.api import logging_pb2 # type: ignore -from google.api import metric_pb2 # type: ignore -from google.api import monitored_resource_pb2 # type: ignore -from google.api import monitoring_pb2 # type: ignore -from google.api import policy_pb2 # type: ignore -from google.api import quota_pb2 # type: ignore -from google.api import service_pb2 # type: ignore -from google.api import source_info_pb2 # type: ignore -from google.api import system_parameter_pb2 # type: ignore -from google.api import usage_pb2 # type: ignore -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import future -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import operation -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.api_core import path_template -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.servicemanagement_v1.services.service_manager import ServiceManagerAsyncClient -from google.cloud.servicemanagement_v1.services.service_manager import ServiceManagerClient -from google.cloud.servicemanagement_v1.services.service_manager import pagers -from google.cloud.servicemanagement_v1.services.service_manager import transports -from google.cloud.servicemanagement_v1.types import resources -from google.cloud.servicemanagement_v1.types import servicemanager -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 api_pb2 # type: ignore -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import source_context_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import type_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore -import google.auth - - -async def mock_async_gen(data, chunk_size=1): - for i in range(0, len(data)): # pragma: NO COVER - chunk = data[i : i + chunk_size] - yield chunk.encode("utf-8") - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - -# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. -# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. -def async_anonymous_credentials(): - if HAS_GOOGLE_AUTH_AIO: - return ga_credentials_async.AnonymousCredentials() - return ga_credentials.AnonymousCredentials() - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - -# If default endpoint template is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint template so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint_template(client): - return "test.{UNIVERSE_DOMAIN}" if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) else client._DEFAULT_ENDPOINT_TEMPLATE - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert ServiceManagerClient._get_default_mtls_endpoint(None) is None - assert ServiceManagerClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert ServiceManagerClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert ServiceManagerClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert ServiceManagerClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert ServiceManagerClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - -def test__read_environment_variables(): - assert ServiceManagerClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert ServiceManagerClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert ServiceManagerClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - ServiceManagerClient._read_environment_variables() - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - assert ServiceManagerClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert ServiceManagerClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert ServiceManagerClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - ServiceManagerClient._read_environment_variables() - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - - with mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"}): - assert ServiceManagerClient._read_environment_variables() == (False, "auto", "foo.com") - -def test__get_client_cert_source(): - mock_provided_cert_source = mock.Mock() - mock_default_cert_source = mock.Mock() - - assert ServiceManagerClient._get_client_cert_source(None, False) is None - assert ServiceManagerClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert ServiceManagerClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source - - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_default_cert_source): - assert ServiceManagerClient._get_client_cert_source(None, True) is mock_default_cert_source - assert ServiceManagerClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(ServiceManagerClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ServiceManagerClient)) -@mock.patch.object(ServiceManagerAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ServiceManagerAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = ServiceManagerClient._DEFAULT_UNIVERSE - default_endpoint = ServiceManagerClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = ServiceManagerClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert ServiceManagerClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert ServiceManagerClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == ServiceManagerClient.DEFAULT_MTLS_ENDPOINT - assert ServiceManagerClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert ServiceManagerClient._get_api_endpoint(None, None, default_universe, "always") == ServiceManagerClient.DEFAULT_MTLS_ENDPOINT - assert ServiceManagerClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == ServiceManagerClient.DEFAULT_MTLS_ENDPOINT - assert ServiceManagerClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert ServiceManagerClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - ServiceManagerClient._get_api_endpoint(None, mock_client_cert_source, mock_universe, "auto") - assert str(excinfo.value) == "mTLS is not supported in any universe other than googleapis.com." - - -def test__get_universe_domain(): - client_universe_domain = "foo.com" - universe_domain_env = "bar.com" - - assert ServiceManagerClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert ServiceManagerClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert ServiceManagerClient._get_universe_domain(None, None) == ServiceManagerClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - ServiceManagerClient._get_universe_domain("", None) - assert str(excinfo.value) == "Universe Domain cannot be an empty string." - - -@pytest.mark.parametrize("client_class,transport_name", [ - (ServiceManagerClient, "grpc"), - (ServiceManagerAsyncClient, "grpc_asyncio"), - (ServiceManagerClient, "rest"), -]) -def test_service_manager_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 == ( - 'servicemanagement.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://servicemanagement.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.ServiceManagerGrpcTransport, "grpc"), - (transports.ServiceManagerGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.ServiceManagerRestTransport, "rest"), -]) -def test_service_manager_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", [ - (ServiceManagerClient, "grpc"), - (ServiceManagerAsyncClient, "grpc_asyncio"), - (ServiceManagerClient, "rest"), -]) -def test_service_manager_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 == ( - 'servicemanagement.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://servicemanagement.googleapis.com' - ) - - -def test_service_manager_client_get_transport_class(): - transport = ServiceManagerClient.get_transport_class() - available_transports = [ - transports.ServiceManagerGrpcTransport, - transports.ServiceManagerRestTransport, - ] - assert transport in available_transports - - transport = ServiceManagerClient.get_transport_class("grpc") - assert transport == transports.ServiceManagerGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ServiceManagerClient, transports.ServiceManagerGrpcTransport, "grpc"), - (ServiceManagerAsyncClient, transports.ServiceManagerGrpcAsyncIOTransport, "grpc_asyncio"), - (ServiceManagerClient, transports.ServiceManagerRestTransport, "rest"), -]) -@mock.patch.object(ServiceManagerClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ServiceManagerClient)) -@mock.patch.object(ServiceManagerAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ServiceManagerAsyncClient)) -def test_service_manager_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(ServiceManagerClient, '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(ServiceManagerClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - client = client_class(transport=transport_name) - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - client = client_class(transport=transport_name) - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (ServiceManagerClient, transports.ServiceManagerGrpcTransport, "grpc", "true"), - (ServiceManagerAsyncClient, transports.ServiceManagerGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (ServiceManagerClient, transports.ServiceManagerGrpcTransport, "grpc", "false"), - (ServiceManagerAsyncClient, transports.ServiceManagerGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (ServiceManagerClient, transports.ServiceManagerRestTransport, "rest", "true"), - (ServiceManagerClient, transports.ServiceManagerRestTransport, "rest", "false"), -]) -@mock.patch.object(ServiceManagerClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ServiceManagerClient)) -@mock.patch.object(ServiceManagerAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ServiceManagerAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_service_manager_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - ServiceManagerClient, ServiceManagerAsyncClient -]) -@mock.patch.object(ServiceManagerClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServiceManagerClient)) -@mock.patch.object(ServiceManagerAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ServiceManagerAsyncClient)) -def test_service_manager_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - client_class.get_mtls_endpoint_and_cert_source() - - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - client_class.get_mtls_endpoint_and_cert_source() - - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - -@pytest.mark.parametrize("client_class", [ - ServiceManagerClient, ServiceManagerAsyncClient -]) -@mock.patch.object(ServiceManagerClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ServiceManagerClient)) -@mock.patch.object(ServiceManagerAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(ServiceManagerAsyncClient)) -def test_service_manager_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = ServiceManagerClient._DEFAULT_UNIVERSE - default_endpoint = ServiceManagerClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = ServiceManagerClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", - # use ClientOptions.api_endpoint as the api endpoint regardless. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"): - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=api_override) - client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == api_override - - # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", - # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - client = client_class(credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == default_endpoint - - # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always", - # use the DEFAULT_MTLS_ENDPOINT as the api endpoint. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - client = client_class(credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - - # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default), - # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist, - # and ClientOptions.universe_domain="bar.com", - # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint. - options = client_options.ClientOptions() - universe_exists = hasattr(options, "universe_domain") - if universe_exists: - options = client_options.ClientOptions(universe_domain=mock_universe) - client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) - else: - client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == (mock_endpoint if universe_exists else default_endpoint) - assert client.universe_domain == (mock_universe if universe_exists else default_universe) - - # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", - # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. - options = client_options.ClientOptions() - if hasattr(options, "universe_domain"): - delattr(options, "universe_domain") - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == default_endpoint - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ServiceManagerClient, transports.ServiceManagerGrpcTransport, "grpc"), - (ServiceManagerAsyncClient, transports.ServiceManagerGrpcAsyncIOTransport, "grpc_asyncio"), - (ServiceManagerClient, transports.ServiceManagerRestTransport, "rest"), -]) -def test_service_manager_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (ServiceManagerClient, transports.ServiceManagerGrpcTransport, "grpc", grpc_helpers), - (ServiceManagerAsyncClient, transports.ServiceManagerGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (ServiceManagerClient, transports.ServiceManagerRestTransport, "rest", None), -]) -def test_service_manager_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_service_manager_client_client_options_from_dict(): - with mock.patch('google.cloud.servicemanagement_v1.services.service_manager.transports.ServiceManagerGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = ServiceManagerClient( - 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", [ - (ServiceManagerClient, transports.ServiceManagerGrpcTransport, "grpc", grpc_helpers), - (ServiceManagerAsyncClient, transports.ServiceManagerGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_service_manager_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "servicemanagement.googleapis.com:443", - credentials=file_creds, - credentials_file=None, - quota_project_id=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', - 'https://www.googleapis.com/auth/service.management', - 'https://www.googleapis.com/auth/service.management.readonly', -), - scopes=None, - default_host="servicemanagement.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - servicemanager.ListServicesRequest, - dict, -]) -def test_list_services(request_type, transport: str = 'grpc'): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_services), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = servicemanager.ListServicesResponse( - next_page_token='next_page_token_value', - ) - response = client.list_services(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = servicemanager.ListServicesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListServicesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_services_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = servicemanager.ListServicesRequest( - producer_project_id='producer_project_id_value', - page_token='page_token_value', - consumer_id='consumer_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_services), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_services(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == servicemanager.ListServicesRequest( - producer_project_id='producer_project_id_value', - page_token='page_token_value', - consumer_id='consumer_id_value', - ) - -def test_list_services_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_services in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_services] = mock_rpc - request = {} - client.list_services(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_services(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_list_services_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = ServiceManagerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.list_services in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.list_services] = mock_rpc - - request = {} - await client.list_services(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_services(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_list_services_async(transport: str = 'grpc_asyncio', request_type=servicemanager.ListServicesRequest): - client = ServiceManagerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_services), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(servicemanager.ListServicesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_services(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = servicemanager.ListServicesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListServicesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_services_async_from_dict(): - await test_list_services_async(request_type=dict) - - -def test_list_services_flattened(): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_services), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = servicemanager.ListServicesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_services( - producer_project_id='producer_project_id_value', - consumer_id='consumer_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].producer_project_id - mock_val = 'producer_project_id_value' - assert arg == mock_val - arg = args[0].consumer_id - mock_val = 'consumer_id_value' - assert arg == mock_val - - -def test_list_services_flattened_error(): - client = ServiceManagerClient( - 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_services( - servicemanager.ListServicesRequest(), - producer_project_id='producer_project_id_value', - consumer_id='consumer_id_value', - ) - -@pytest.mark.asyncio -async def test_list_services_flattened_async(): - client = ServiceManagerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_services), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = servicemanager.ListServicesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(servicemanager.ListServicesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_services( - producer_project_id='producer_project_id_value', - consumer_id='consumer_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].producer_project_id - mock_val = 'producer_project_id_value' - assert arg == mock_val - arg = args[0].consumer_id - mock_val = 'consumer_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_list_services_flattened_error_async(): - client = ServiceManagerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_services( - servicemanager.ListServicesRequest(), - producer_project_id='producer_project_id_value', - consumer_id='consumer_id_value', - ) - - -def test_list_services_pager(transport_name: str = "grpc"): - client = ServiceManagerClient( - 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_services), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - servicemanager.ListServicesResponse( - services=[ - resources.ManagedService(), - resources.ManagedService(), - resources.ManagedService(), - ], - next_page_token='abc', - ), - servicemanager.ListServicesResponse( - services=[], - next_page_token='def', - ), - servicemanager.ListServicesResponse( - services=[ - resources.ManagedService(), - ], - next_page_token='ghi', - ), - servicemanager.ListServicesResponse( - services=[ - resources.ManagedService(), - resources.ManagedService(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - pager = client.list_services(request={}, retry=retry, timeout=timeout) - - assert pager._metadata == expected_metadata - assert pager._retry == retry - assert pager._timeout == timeout - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, resources.ManagedService) - for i in results) -def test_list_services_pages(transport_name: str = "grpc"): - client = ServiceManagerClient( - 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_services), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - servicemanager.ListServicesResponse( - services=[ - resources.ManagedService(), - resources.ManagedService(), - resources.ManagedService(), - ], - next_page_token='abc', - ), - servicemanager.ListServicesResponse( - services=[], - next_page_token='def', - ), - servicemanager.ListServicesResponse( - services=[ - resources.ManagedService(), - ], - next_page_token='ghi', - ), - servicemanager.ListServicesResponse( - services=[ - resources.ManagedService(), - resources.ManagedService(), - ], - ), - RuntimeError, - ) - pages = list(client.list_services(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_services_async_pager(): - client = ServiceManagerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_services), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - servicemanager.ListServicesResponse( - services=[ - resources.ManagedService(), - resources.ManagedService(), - resources.ManagedService(), - ], - next_page_token='abc', - ), - servicemanager.ListServicesResponse( - services=[], - next_page_token='def', - ), - servicemanager.ListServicesResponse( - services=[ - resources.ManagedService(), - ], - next_page_token='ghi', - ), - servicemanager.ListServicesResponse( - services=[ - resources.ManagedService(), - resources.ManagedService(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_services(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, resources.ManagedService) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_services_async_pages(): - client = ServiceManagerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_services), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - servicemanager.ListServicesResponse( - services=[ - resources.ManagedService(), - resources.ManagedService(), - resources.ManagedService(), - ], - next_page_token='abc', - ), - servicemanager.ListServicesResponse( - services=[], - next_page_token='def', - ), - servicemanager.ListServicesResponse( - services=[ - resources.ManagedService(), - ], - next_page_token='ghi', - ), - servicemanager.ListServicesResponse( - services=[ - resources.ManagedService(), - resources.ManagedService(), - ], - ), - 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_services(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", [ - servicemanager.GetServiceRequest, - dict, -]) -def test_get_service(request_type, transport: str = 'grpc'): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_service), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.ManagedService( - service_name='service_name_value', - producer_project_id='producer_project_id_value', - ) - response = client.get_service(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = servicemanager.GetServiceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.ManagedService) - assert response.service_name == 'service_name_value' - assert response.producer_project_id == 'producer_project_id_value' - - -def test_get_service_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = servicemanager.GetServiceRequest( - service_name='service_name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_service), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_service(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == servicemanager.GetServiceRequest( - service_name='service_name_value', - ) - -def test_get_service_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_service in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_service] = mock_rpc - request = {} - client.get_service(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_service(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_get_service_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = ServiceManagerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.get_service in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.get_service] = mock_rpc - - request = {} - await client.get_service(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_service(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_get_service_async(transport: str = 'grpc_asyncio', request_type=servicemanager.GetServiceRequest): - client = ServiceManagerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_service), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.ManagedService( - service_name='service_name_value', - producer_project_id='producer_project_id_value', - )) - response = await client.get_service(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = servicemanager.GetServiceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.ManagedService) - assert response.service_name == 'service_name_value' - assert response.producer_project_id == 'producer_project_id_value' - - -@pytest.mark.asyncio -async def test_get_service_async_from_dict(): - await test_get_service_async(request_type=dict) - -def test_get_service_field_headers(): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = servicemanager.GetServiceRequest() - - request.service_name = 'service_name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_service), - '__call__') as call: - call.return_value = resources.ManagedService() - client.get_service(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'service_name=service_name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_service_field_headers_async(): - client = ServiceManagerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = servicemanager.GetServiceRequest() - - request.service_name = 'service_name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_service), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.ManagedService()) - await client.get_service(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'service_name=service_name_value', - ) in kw['metadata'] - - -def test_get_service_flattened(): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_service), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.ManagedService() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_service( - service_name='service_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].service_name - mock_val = 'service_name_value' - assert arg == mock_val - - -def test_get_service_flattened_error(): - client = ServiceManagerClient( - 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_service( - servicemanager.GetServiceRequest(), - service_name='service_name_value', - ) - -@pytest.mark.asyncio -async def test_get_service_flattened_async(): - client = ServiceManagerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_service), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.ManagedService() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.ManagedService()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_service( - service_name='service_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].service_name - mock_val = 'service_name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_service_flattened_error_async(): - client = ServiceManagerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_service( - servicemanager.GetServiceRequest(), - service_name='service_name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - servicemanager.CreateServiceRequest, - dict, -]) -def test_create_service(request_type, transport: str = 'grpc'): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_service), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.create_service(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = servicemanager.CreateServiceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_create_service_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = servicemanager.CreateServiceRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_service), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_service(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == servicemanager.CreateServiceRequest( - ) - -def test_create_service_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.create_service in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.create_service] = mock_rpc - request = {} - client.create_service(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.create_service(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_create_service_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = ServiceManagerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.create_service in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.create_service] = mock_rpc - - request = {} - await client.create_service(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.create_service(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_create_service_async(transport: str = 'grpc_asyncio', request_type=servicemanager.CreateServiceRequest): - client = ServiceManagerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_service), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.create_service(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = servicemanager.CreateServiceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_create_service_async_from_dict(): - await test_create_service_async(request_type=dict) - - -def test_create_service_flattened(): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_service), - '__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_service( - service=resources.ManagedService(service_name='service_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].service - mock_val = resources.ManagedService(service_name='service_name_value') - assert arg == mock_val - - -def test_create_service_flattened_error(): - client = ServiceManagerClient( - 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_service( - servicemanager.CreateServiceRequest(), - service=resources.ManagedService(service_name='service_name_value'), - ) - -@pytest.mark.asyncio -async def test_create_service_flattened_async(): - client = ServiceManagerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_service), - '__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_service( - service=resources.ManagedService(service_name='service_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].service - mock_val = resources.ManagedService(service_name='service_name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_service_flattened_error_async(): - client = ServiceManagerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_service( - servicemanager.CreateServiceRequest(), - service=resources.ManagedService(service_name='service_name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - servicemanager.DeleteServiceRequest, - dict, -]) -def test_delete_service(request_type, transport: str = 'grpc'): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_service), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.delete_service(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = servicemanager.DeleteServiceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_delete_service_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = servicemanager.DeleteServiceRequest( - service_name='service_name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_service), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_service(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == servicemanager.DeleteServiceRequest( - service_name='service_name_value', - ) - -def test_delete_service_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.delete_service in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.delete_service] = mock_rpc - request = {} - client.delete_service(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.delete_service(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_delete_service_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = ServiceManagerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.delete_service in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.delete_service] = mock_rpc - - request = {} - await client.delete_service(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.delete_service(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_delete_service_async(transport: str = 'grpc_asyncio', request_type=servicemanager.DeleteServiceRequest): - client = ServiceManagerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_service), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.delete_service(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = servicemanager.DeleteServiceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_delete_service_async_from_dict(): - await test_delete_service_async(request_type=dict) - -def test_delete_service_field_headers(): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = servicemanager.DeleteServiceRequest() - - request.service_name = 'service_name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_service), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_service(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'service_name=service_name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_delete_service_field_headers_async(): - client = ServiceManagerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = servicemanager.DeleteServiceRequest() - - request.service_name = 'service_name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_service), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.delete_service(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'service_name=service_name_value', - ) in kw['metadata'] - - -def test_delete_service_flattened(): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_service), - '__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_service( - service_name='service_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].service_name - mock_val = 'service_name_value' - assert arg == mock_val - - -def test_delete_service_flattened_error(): - client = ServiceManagerClient( - 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_service( - servicemanager.DeleteServiceRequest(), - service_name='service_name_value', - ) - -@pytest.mark.asyncio -async def test_delete_service_flattened_async(): - client = ServiceManagerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_service), - '__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_service( - service_name='service_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].service_name - mock_val = 'service_name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_delete_service_flattened_error_async(): - client = ServiceManagerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_service( - servicemanager.DeleteServiceRequest(), - service_name='service_name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - servicemanager.UndeleteServiceRequest, - dict, -]) -def test_undelete_service(request_type, transport: str = 'grpc'): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.undelete_service), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.undelete_service(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = servicemanager.UndeleteServiceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_undelete_service_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = servicemanager.UndeleteServiceRequest( - service_name='service_name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.undelete_service), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.undelete_service(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == servicemanager.UndeleteServiceRequest( - service_name='service_name_value', - ) - -def test_undelete_service_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.undelete_service in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.undelete_service] = mock_rpc - request = {} - client.undelete_service(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.undelete_service(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_undelete_service_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = ServiceManagerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.undelete_service in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.undelete_service] = mock_rpc - - request = {} - await client.undelete_service(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.undelete_service(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_undelete_service_async(transport: str = 'grpc_asyncio', request_type=servicemanager.UndeleteServiceRequest): - client = ServiceManagerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.undelete_service), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.undelete_service(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = servicemanager.UndeleteServiceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_undelete_service_async_from_dict(): - await test_undelete_service_async(request_type=dict) - -def test_undelete_service_field_headers(): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = servicemanager.UndeleteServiceRequest() - - request.service_name = 'service_name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.undelete_service), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.undelete_service(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'service_name=service_name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_undelete_service_field_headers_async(): - client = ServiceManagerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = servicemanager.UndeleteServiceRequest() - - request.service_name = 'service_name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.undelete_service), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.undelete_service(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'service_name=service_name_value', - ) in kw['metadata'] - - -def test_undelete_service_flattened(): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.undelete_service), - '__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.undelete_service( - service_name='service_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].service_name - mock_val = 'service_name_value' - assert arg == mock_val - - -def test_undelete_service_flattened_error(): - client = ServiceManagerClient( - 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.undelete_service( - servicemanager.UndeleteServiceRequest(), - service_name='service_name_value', - ) - -@pytest.mark.asyncio -async def test_undelete_service_flattened_async(): - client = ServiceManagerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.undelete_service), - '__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.undelete_service( - service_name='service_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].service_name - mock_val = 'service_name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_undelete_service_flattened_error_async(): - client = ServiceManagerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.undelete_service( - servicemanager.UndeleteServiceRequest(), - service_name='service_name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - servicemanager.ListServiceConfigsRequest, - dict, -]) -def test_list_service_configs(request_type, transport: str = 'grpc'): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_service_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = servicemanager.ListServiceConfigsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_service_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = servicemanager.ListServiceConfigsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListServiceConfigsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_service_configs_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = servicemanager.ListServiceConfigsRequest( - service_name='service_name_value', - page_token='page_token_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_service_configs), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_service_configs(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == servicemanager.ListServiceConfigsRequest( - service_name='service_name_value', - page_token='page_token_value', - ) - -def test_list_service_configs_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_service_configs in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_service_configs] = mock_rpc - request = {} - client.list_service_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_service_configs(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_list_service_configs_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = ServiceManagerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.list_service_configs in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.list_service_configs] = mock_rpc - - request = {} - await client.list_service_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_service_configs(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_list_service_configs_async(transport: str = 'grpc_asyncio', request_type=servicemanager.ListServiceConfigsRequest): - client = ServiceManagerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_service_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(servicemanager.ListServiceConfigsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_service_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = servicemanager.ListServiceConfigsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListServiceConfigsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_service_configs_async_from_dict(): - await test_list_service_configs_async(request_type=dict) - -def test_list_service_configs_field_headers(): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = servicemanager.ListServiceConfigsRequest() - - request.service_name = 'service_name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_service_configs), - '__call__') as call: - call.return_value = servicemanager.ListServiceConfigsResponse() - client.list_service_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'service_name=service_name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_list_service_configs_field_headers_async(): - client = ServiceManagerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = servicemanager.ListServiceConfigsRequest() - - request.service_name = 'service_name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_service_configs), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(servicemanager.ListServiceConfigsResponse()) - await client.list_service_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'service_name=service_name_value', - ) in kw['metadata'] - - -def test_list_service_configs_flattened(): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_service_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = servicemanager.ListServiceConfigsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_service_configs( - service_name='service_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].service_name - mock_val = 'service_name_value' - assert arg == mock_val - - -def test_list_service_configs_flattened_error(): - client = ServiceManagerClient( - 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_service_configs( - servicemanager.ListServiceConfigsRequest(), - service_name='service_name_value', - ) - -@pytest.mark.asyncio -async def test_list_service_configs_flattened_async(): - client = ServiceManagerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_service_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = servicemanager.ListServiceConfigsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(servicemanager.ListServiceConfigsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_service_configs( - service_name='service_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].service_name - mock_val = 'service_name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_list_service_configs_flattened_error_async(): - client = ServiceManagerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_service_configs( - servicemanager.ListServiceConfigsRequest(), - service_name='service_name_value', - ) - - -def test_list_service_configs_pager(transport_name: str = "grpc"): - client = ServiceManagerClient( - 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_service_configs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - servicemanager.ListServiceConfigsResponse( - service_configs=[ - service_pb2.Service(), - service_pb2.Service(), - service_pb2.Service(), - ], - next_page_token='abc', - ), - servicemanager.ListServiceConfigsResponse( - service_configs=[], - next_page_token='def', - ), - servicemanager.ListServiceConfigsResponse( - service_configs=[ - service_pb2.Service(), - ], - next_page_token='ghi', - ), - servicemanager.ListServiceConfigsResponse( - service_configs=[ - service_pb2.Service(), - service_pb2.Service(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('service_name', ''), - )), - ) - pager = client.list_service_configs(request={}, retry=retry, timeout=timeout) - - assert pager._metadata == expected_metadata - assert pager._retry == retry - assert pager._timeout == timeout - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, service_pb2.Service) - for i in results) -def test_list_service_configs_pages(transport_name: str = "grpc"): - client = ServiceManagerClient( - 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_service_configs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - servicemanager.ListServiceConfigsResponse( - service_configs=[ - service_pb2.Service(), - service_pb2.Service(), - service_pb2.Service(), - ], - next_page_token='abc', - ), - servicemanager.ListServiceConfigsResponse( - service_configs=[], - next_page_token='def', - ), - servicemanager.ListServiceConfigsResponse( - service_configs=[ - service_pb2.Service(), - ], - next_page_token='ghi', - ), - servicemanager.ListServiceConfigsResponse( - service_configs=[ - service_pb2.Service(), - service_pb2.Service(), - ], - ), - RuntimeError, - ) - pages = list(client.list_service_configs(request={}).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.asyncio -async def test_list_service_configs_async_pager(): - client = ServiceManagerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_service_configs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - servicemanager.ListServiceConfigsResponse( - service_configs=[ - service_pb2.Service(), - service_pb2.Service(), - service_pb2.Service(), - ], - next_page_token='abc', - ), - servicemanager.ListServiceConfigsResponse( - service_configs=[], - next_page_token='def', - ), - servicemanager.ListServiceConfigsResponse( - service_configs=[ - service_pb2.Service(), - ], - next_page_token='ghi', - ), - servicemanager.ListServiceConfigsResponse( - service_configs=[ - service_pb2.Service(), - service_pb2.Service(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_service_configs(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, service_pb2.Service) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_service_configs_async_pages(): - client = ServiceManagerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_service_configs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - servicemanager.ListServiceConfigsResponse( - service_configs=[ - service_pb2.Service(), - service_pb2.Service(), - service_pb2.Service(), - ], - next_page_token='abc', - ), - servicemanager.ListServiceConfigsResponse( - service_configs=[], - next_page_token='def', - ), - servicemanager.ListServiceConfigsResponse( - service_configs=[ - service_pb2.Service(), - ], - next_page_token='ghi', - ), - servicemanager.ListServiceConfigsResponse( - service_configs=[ - service_pb2.Service(), - service_pb2.Service(), - ], - ), - 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_service_configs(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", [ - servicemanager.GetServiceConfigRequest, - dict, -]) -def test_get_service_config(request_type, transport: str = 'grpc'): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_service_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service_pb2.Service( - name='name_value', - title='title_value', - producer_project_id='producer_project_id_value', - id='id_value', - ) - response = client.get_service_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = servicemanager.GetServiceConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, service_pb2.Service) - assert response.name == 'name_value' - assert response.title == 'title_value' - assert response.producer_project_id == 'producer_project_id_value' - assert response.id == 'id_value' - - -def test_get_service_config_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = servicemanager.GetServiceConfigRequest( - service_name='service_name_value', - config_id='config_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_service_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_service_config(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == servicemanager.GetServiceConfigRequest( - service_name='service_name_value', - config_id='config_id_value', - ) - -def test_get_service_config_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_service_config in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_service_config] = mock_rpc - request = {} - client.get_service_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_service_config(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_get_service_config_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = ServiceManagerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.get_service_config in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.get_service_config] = mock_rpc - - request = {} - await client.get_service_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_service_config(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_get_service_config_async(transport: str = 'grpc_asyncio', request_type=servicemanager.GetServiceConfigRequest): - client = ServiceManagerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_service_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(service_pb2.Service( - name='name_value', - title='title_value', - producer_project_id='producer_project_id_value', - id='id_value', - )) - response = await client.get_service_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = servicemanager.GetServiceConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, service_pb2.Service) - assert response.name == 'name_value' - assert response.title == 'title_value' - assert response.producer_project_id == 'producer_project_id_value' - assert response.id == 'id_value' - - -@pytest.mark.asyncio -async def test_get_service_config_async_from_dict(): - await test_get_service_config_async(request_type=dict) - -def test_get_service_config_field_headers(): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = servicemanager.GetServiceConfigRequest() - - request.service_name = 'service_name_value' - request.config_id = 'config_id_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_service_config), - '__call__') as call: - call.return_value = service_pb2.Service() - client.get_service_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'service_name=service_name_value&config_id=config_id_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_service_config_field_headers_async(): - client = ServiceManagerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = servicemanager.GetServiceConfigRequest() - - request.service_name = 'service_name_value' - request.config_id = 'config_id_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_service_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service_pb2.Service()) - await client.get_service_config(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', - 'service_name=service_name_value&config_id=config_id_value', - ) in kw['metadata'] - - -def test_get_service_config_flattened(): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_service_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service_pb2.Service() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_service_config( - service_name='service_name_value', - config_id='config_id_value', - view=servicemanager.GetServiceConfigRequest.ConfigView.FULL, - ) - - # 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].service_name - mock_val = 'service_name_value' - assert arg == mock_val - arg = args[0].config_id - mock_val = 'config_id_value' - assert arg == mock_val - arg = args[0].view - mock_val = servicemanager.GetServiceConfigRequest.ConfigView.FULL - assert arg == mock_val - - -def test_get_service_config_flattened_error(): - client = ServiceManagerClient( - 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_service_config( - servicemanager.GetServiceConfigRequest(), - service_name='service_name_value', - config_id='config_id_value', - view=servicemanager.GetServiceConfigRequest.ConfigView.FULL, - ) - -@pytest.mark.asyncio -async def test_get_service_config_flattened_async(): - client = ServiceManagerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_service_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service_pb2.Service() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service_pb2.Service()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_service_config( - service_name='service_name_value', - config_id='config_id_value', - view=servicemanager.GetServiceConfigRequest.ConfigView.FULL, - ) - - # 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].service_name - mock_val = 'service_name_value' - assert arg == mock_val - arg = args[0].config_id - mock_val = 'config_id_value' - assert arg == mock_val - arg = args[0].view - mock_val = servicemanager.GetServiceConfigRequest.ConfigView.FULL - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_service_config_flattened_error_async(): - client = ServiceManagerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_service_config( - servicemanager.GetServiceConfigRequest(), - service_name='service_name_value', - config_id='config_id_value', - view=servicemanager.GetServiceConfigRequest.ConfigView.FULL, - ) - - -@pytest.mark.parametrize("request_type", [ - servicemanager.CreateServiceConfigRequest, - dict, -]) -def test_create_service_config(request_type, transport: str = 'grpc'): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_service_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service_pb2.Service( - name='name_value', - title='title_value', - producer_project_id='producer_project_id_value', - id='id_value', - ) - response = client.create_service_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = servicemanager.CreateServiceConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, service_pb2.Service) - assert response.name == 'name_value' - assert response.title == 'title_value' - assert response.producer_project_id == 'producer_project_id_value' - assert response.id == 'id_value' - - -def test_create_service_config_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = servicemanager.CreateServiceConfigRequest( - service_name='service_name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_service_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_service_config(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == servicemanager.CreateServiceConfigRequest( - service_name='service_name_value', - ) - -def test_create_service_config_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.create_service_config in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.create_service_config] = mock_rpc - request = {} - client.create_service_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_service_config(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_create_service_config_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = ServiceManagerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.create_service_config in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.create_service_config] = mock_rpc - - request = {} - await client.create_service_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.create_service_config(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_create_service_config_async(transport: str = 'grpc_asyncio', request_type=servicemanager.CreateServiceConfigRequest): - client = ServiceManagerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_service_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(service_pb2.Service( - name='name_value', - title='title_value', - producer_project_id='producer_project_id_value', - id='id_value', - )) - response = await client.create_service_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = servicemanager.CreateServiceConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, service_pb2.Service) - assert response.name == 'name_value' - assert response.title == 'title_value' - assert response.producer_project_id == 'producer_project_id_value' - assert response.id == 'id_value' - - -@pytest.mark.asyncio -async def test_create_service_config_async_from_dict(): - await test_create_service_config_async(request_type=dict) - -def test_create_service_config_field_headers(): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = servicemanager.CreateServiceConfigRequest() - - request.service_name = 'service_name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_service_config), - '__call__') as call: - call.return_value = service_pb2.Service() - client.create_service_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'service_name=service_name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_create_service_config_field_headers_async(): - client = ServiceManagerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = servicemanager.CreateServiceConfigRequest() - - request.service_name = 'service_name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_service_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service_pb2.Service()) - await client.create_service_config(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', - 'service_name=service_name_value', - ) in kw['metadata'] - - -def test_create_service_config_flattened(): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_service_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service_pb2.Service() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_service_config( - service_name='service_name_value', - service_config=service_pb2.Service(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].service_name - mock_val = 'service_name_value' - assert arg == mock_val - arg = args[0].service_config - mock_val = service_pb2.Service(name='name_value') - assert arg == mock_val - - -def test_create_service_config_flattened_error(): - client = ServiceManagerClient( - 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_service_config( - servicemanager.CreateServiceConfigRequest(), - service_name='service_name_value', - service_config=service_pb2.Service(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_create_service_config_flattened_async(): - client = ServiceManagerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_service_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service_pb2.Service() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service_pb2.Service()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_service_config( - service_name='service_name_value', - service_config=service_pb2.Service(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].service_name - mock_val = 'service_name_value' - assert arg == mock_val - arg = args[0].service_config - mock_val = service_pb2.Service(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_service_config_flattened_error_async(): - client = ServiceManagerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_service_config( - servicemanager.CreateServiceConfigRequest(), - service_name='service_name_value', - service_config=service_pb2.Service(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - servicemanager.SubmitConfigSourceRequest, - dict, -]) -def test_submit_config_source(request_type, transport: str = 'grpc'): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.submit_config_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.submit_config_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = servicemanager.SubmitConfigSourceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_submit_config_source_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = servicemanager.SubmitConfigSourceRequest( - service_name='service_name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.submit_config_source), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.submit_config_source(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == servicemanager.SubmitConfigSourceRequest( - service_name='service_name_value', - ) - -def test_submit_config_source_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.submit_config_source in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.submit_config_source] = mock_rpc - request = {} - client.submit_config_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.submit_config_source(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_submit_config_source_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = ServiceManagerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.submit_config_source in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.submit_config_source] = mock_rpc - - request = {} - await client.submit_config_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.submit_config_source(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_submit_config_source_async(transport: str = 'grpc_asyncio', request_type=servicemanager.SubmitConfigSourceRequest): - client = ServiceManagerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.submit_config_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.submit_config_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = servicemanager.SubmitConfigSourceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_submit_config_source_async_from_dict(): - await test_submit_config_source_async(request_type=dict) - -def test_submit_config_source_field_headers(): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = servicemanager.SubmitConfigSourceRequest() - - request.service_name = 'service_name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.submit_config_source), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.submit_config_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'service_name=service_name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_submit_config_source_field_headers_async(): - client = ServiceManagerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = servicemanager.SubmitConfigSourceRequest() - - request.service_name = 'service_name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.submit_config_source), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.submit_config_source(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'service_name=service_name_value', - ) in kw['metadata'] - - -def test_submit_config_source_flattened(): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.submit_config_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.submit_config_source( - service_name='service_name_value', - config_source=resources.ConfigSource(id='id_value'), - validate_only=True, - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].service_name - mock_val = 'service_name_value' - assert arg == mock_val - arg = args[0].config_source - mock_val = resources.ConfigSource(id='id_value') - assert arg == mock_val - arg = args[0].validate_only - mock_val = True - assert arg == mock_val - - -def test_submit_config_source_flattened_error(): - client = ServiceManagerClient( - 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.submit_config_source( - servicemanager.SubmitConfigSourceRequest(), - service_name='service_name_value', - config_source=resources.ConfigSource(id='id_value'), - validate_only=True, - ) - -@pytest.mark.asyncio -async def test_submit_config_source_flattened_async(): - client = ServiceManagerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.submit_config_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.submit_config_source( - service_name='service_name_value', - config_source=resources.ConfigSource(id='id_value'), - validate_only=True, - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].service_name - mock_val = 'service_name_value' - assert arg == mock_val - arg = args[0].config_source - mock_val = resources.ConfigSource(id='id_value') - assert arg == mock_val - arg = args[0].validate_only - mock_val = True - assert arg == mock_val - -@pytest.mark.asyncio -async def test_submit_config_source_flattened_error_async(): - client = ServiceManagerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.submit_config_source( - servicemanager.SubmitConfigSourceRequest(), - service_name='service_name_value', - config_source=resources.ConfigSource(id='id_value'), - validate_only=True, - ) - - -@pytest.mark.parametrize("request_type", [ - servicemanager.ListServiceRolloutsRequest, - dict, -]) -def test_list_service_rollouts(request_type, transport: str = 'grpc'): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_service_rollouts), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = servicemanager.ListServiceRolloutsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_service_rollouts(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = servicemanager.ListServiceRolloutsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListServiceRolloutsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_service_rollouts_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = servicemanager.ListServiceRolloutsRequest( - service_name='service_name_value', - page_token='page_token_value', - filter='filter_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_service_rollouts), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_service_rollouts(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == servicemanager.ListServiceRolloutsRequest( - service_name='service_name_value', - page_token='page_token_value', - filter='filter_value', - ) - -def test_list_service_rollouts_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_service_rollouts in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_service_rollouts] = mock_rpc - request = {} - client.list_service_rollouts(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_service_rollouts(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_list_service_rollouts_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = ServiceManagerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.list_service_rollouts in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.list_service_rollouts] = mock_rpc - - request = {} - await client.list_service_rollouts(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_service_rollouts(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_list_service_rollouts_async(transport: str = 'grpc_asyncio', request_type=servicemanager.ListServiceRolloutsRequest): - client = ServiceManagerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_service_rollouts), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(servicemanager.ListServiceRolloutsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_service_rollouts(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = servicemanager.ListServiceRolloutsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListServiceRolloutsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_service_rollouts_async_from_dict(): - await test_list_service_rollouts_async(request_type=dict) - -def test_list_service_rollouts_field_headers(): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = servicemanager.ListServiceRolloutsRequest() - - request.service_name = 'service_name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_service_rollouts), - '__call__') as call: - call.return_value = servicemanager.ListServiceRolloutsResponse() - client.list_service_rollouts(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'service_name=service_name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_list_service_rollouts_field_headers_async(): - client = ServiceManagerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = servicemanager.ListServiceRolloutsRequest() - - request.service_name = 'service_name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_service_rollouts), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(servicemanager.ListServiceRolloutsResponse()) - await client.list_service_rollouts(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', - 'service_name=service_name_value', - ) in kw['metadata'] - - -def test_list_service_rollouts_flattened(): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_service_rollouts), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = servicemanager.ListServiceRolloutsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_service_rollouts( - service_name='service_name_value', - filter='filter_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].service_name - mock_val = 'service_name_value' - assert arg == mock_val - arg = args[0].filter - mock_val = 'filter_value' - assert arg == mock_val - - -def test_list_service_rollouts_flattened_error(): - client = ServiceManagerClient( - 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_service_rollouts( - servicemanager.ListServiceRolloutsRequest(), - service_name='service_name_value', - filter='filter_value', - ) - -@pytest.mark.asyncio -async def test_list_service_rollouts_flattened_async(): - client = ServiceManagerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_service_rollouts), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = servicemanager.ListServiceRolloutsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(servicemanager.ListServiceRolloutsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_service_rollouts( - service_name='service_name_value', - filter='filter_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].service_name - mock_val = 'service_name_value' - assert arg == mock_val - arg = args[0].filter - mock_val = 'filter_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_list_service_rollouts_flattened_error_async(): - client = ServiceManagerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_service_rollouts( - servicemanager.ListServiceRolloutsRequest(), - service_name='service_name_value', - filter='filter_value', - ) - - -def test_list_service_rollouts_pager(transport_name: str = "grpc"): - client = ServiceManagerClient( - 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_service_rollouts), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - servicemanager.ListServiceRolloutsResponse( - rollouts=[ - resources.Rollout(), - resources.Rollout(), - resources.Rollout(), - ], - next_page_token='abc', - ), - servicemanager.ListServiceRolloutsResponse( - rollouts=[], - next_page_token='def', - ), - servicemanager.ListServiceRolloutsResponse( - rollouts=[ - resources.Rollout(), - ], - next_page_token='ghi', - ), - servicemanager.ListServiceRolloutsResponse( - rollouts=[ - resources.Rollout(), - resources.Rollout(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('service_name', ''), - )), - ) - pager = client.list_service_rollouts(request={}, retry=retry, timeout=timeout) - - assert pager._metadata == expected_metadata - assert pager._retry == retry - assert pager._timeout == timeout - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, resources.Rollout) - for i in results) -def test_list_service_rollouts_pages(transport_name: str = "grpc"): - client = ServiceManagerClient( - 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_service_rollouts), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - servicemanager.ListServiceRolloutsResponse( - rollouts=[ - resources.Rollout(), - resources.Rollout(), - resources.Rollout(), - ], - next_page_token='abc', - ), - servicemanager.ListServiceRolloutsResponse( - rollouts=[], - next_page_token='def', - ), - servicemanager.ListServiceRolloutsResponse( - rollouts=[ - resources.Rollout(), - ], - next_page_token='ghi', - ), - servicemanager.ListServiceRolloutsResponse( - rollouts=[ - resources.Rollout(), - resources.Rollout(), - ], - ), - RuntimeError, - ) - pages = list(client.list_service_rollouts(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_service_rollouts_async_pager(): - client = ServiceManagerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_service_rollouts), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - servicemanager.ListServiceRolloutsResponse( - rollouts=[ - resources.Rollout(), - resources.Rollout(), - resources.Rollout(), - ], - next_page_token='abc', - ), - servicemanager.ListServiceRolloutsResponse( - rollouts=[], - next_page_token='def', - ), - servicemanager.ListServiceRolloutsResponse( - rollouts=[ - resources.Rollout(), - ], - next_page_token='ghi', - ), - servicemanager.ListServiceRolloutsResponse( - rollouts=[ - resources.Rollout(), - resources.Rollout(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_service_rollouts(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, resources.Rollout) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_service_rollouts_async_pages(): - client = ServiceManagerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_service_rollouts), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - servicemanager.ListServiceRolloutsResponse( - rollouts=[ - resources.Rollout(), - resources.Rollout(), - resources.Rollout(), - ], - next_page_token='abc', - ), - servicemanager.ListServiceRolloutsResponse( - rollouts=[], - next_page_token='def', - ), - servicemanager.ListServiceRolloutsResponse( - rollouts=[ - resources.Rollout(), - ], - next_page_token='ghi', - ), - servicemanager.ListServiceRolloutsResponse( - rollouts=[ - resources.Rollout(), - resources.Rollout(), - ], - ), - 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_service_rollouts(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", [ - servicemanager.GetServiceRolloutRequest, - dict, -]) -def test_get_service_rollout(request_type, transport: str = 'grpc'): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_service_rollout), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.Rollout( - rollout_id='rollout_id_value', - created_by='created_by_value', - status=resources.Rollout.RolloutStatus.IN_PROGRESS, - service_name='service_name_value', - ) - response = client.get_service_rollout(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = servicemanager.GetServiceRolloutRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.Rollout) - assert response.rollout_id == 'rollout_id_value' - assert response.created_by == 'created_by_value' - assert response.status == resources.Rollout.RolloutStatus.IN_PROGRESS - assert response.service_name == 'service_name_value' - - -def test_get_service_rollout_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = servicemanager.GetServiceRolloutRequest( - service_name='service_name_value', - rollout_id='rollout_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_service_rollout), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_service_rollout(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == servicemanager.GetServiceRolloutRequest( - service_name='service_name_value', - rollout_id='rollout_id_value', - ) - -def test_get_service_rollout_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_service_rollout in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_service_rollout] = mock_rpc - request = {} - client.get_service_rollout(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_service_rollout(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_get_service_rollout_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = ServiceManagerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.get_service_rollout in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.get_service_rollout] = mock_rpc - - request = {} - await client.get_service_rollout(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_service_rollout(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_get_service_rollout_async(transport: str = 'grpc_asyncio', request_type=servicemanager.GetServiceRolloutRequest): - client = ServiceManagerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_service_rollout), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.Rollout( - rollout_id='rollout_id_value', - created_by='created_by_value', - status=resources.Rollout.RolloutStatus.IN_PROGRESS, - service_name='service_name_value', - )) - response = await client.get_service_rollout(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = servicemanager.GetServiceRolloutRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.Rollout) - assert response.rollout_id == 'rollout_id_value' - assert response.created_by == 'created_by_value' - assert response.status == resources.Rollout.RolloutStatus.IN_PROGRESS - assert response.service_name == 'service_name_value' - - -@pytest.mark.asyncio -async def test_get_service_rollout_async_from_dict(): - await test_get_service_rollout_async(request_type=dict) - -def test_get_service_rollout_field_headers(): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = servicemanager.GetServiceRolloutRequest() - - request.service_name = 'service_name_value' - request.rollout_id = 'rollout_id_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_service_rollout), - '__call__') as call: - call.return_value = resources.Rollout() - client.get_service_rollout(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'service_name=service_name_value&rollout_id=rollout_id_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_service_rollout_field_headers_async(): - client = ServiceManagerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = servicemanager.GetServiceRolloutRequest() - - request.service_name = 'service_name_value' - request.rollout_id = 'rollout_id_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_service_rollout), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Rollout()) - await client.get_service_rollout(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', - 'service_name=service_name_value&rollout_id=rollout_id_value', - ) in kw['metadata'] - - -def test_get_service_rollout_flattened(): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_service_rollout), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.Rollout() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_service_rollout( - service_name='service_name_value', - rollout_id='rollout_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].service_name - mock_val = 'service_name_value' - assert arg == mock_val - arg = args[0].rollout_id - mock_val = 'rollout_id_value' - assert arg == mock_val - - -def test_get_service_rollout_flattened_error(): - client = ServiceManagerClient( - 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_service_rollout( - servicemanager.GetServiceRolloutRequest(), - service_name='service_name_value', - rollout_id='rollout_id_value', - ) - -@pytest.mark.asyncio -async def test_get_service_rollout_flattened_async(): - client = ServiceManagerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_service_rollout), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.Rollout() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Rollout()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_service_rollout( - service_name='service_name_value', - rollout_id='rollout_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].service_name - mock_val = 'service_name_value' - assert arg == mock_val - arg = args[0].rollout_id - mock_val = 'rollout_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_service_rollout_flattened_error_async(): - client = ServiceManagerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_service_rollout( - servicemanager.GetServiceRolloutRequest(), - service_name='service_name_value', - rollout_id='rollout_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - servicemanager.CreateServiceRolloutRequest, - dict, -]) -def test_create_service_rollout(request_type, transport: str = 'grpc'): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_service_rollout), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.create_service_rollout(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = servicemanager.CreateServiceRolloutRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_create_service_rollout_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = servicemanager.CreateServiceRolloutRequest( - service_name='service_name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_service_rollout), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_service_rollout(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == servicemanager.CreateServiceRolloutRequest( - service_name='service_name_value', - ) - -def test_create_service_rollout_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.create_service_rollout in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.create_service_rollout] = mock_rpc - request = {} - client.create_service_rollout(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.create_service_rollout(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_create_service_rollout_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = ServiceManagerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.create_service_rollout in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.create_service_rollout] = mock_rpc - - request = {} - await client.create_service_rollout(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.create_service_rollout(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_create_service_rollout_async(transport: str = 'grpc_asyncio', request_type=servicemanager.CreateServiceRolloutRequest): - client = ServiceManagerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_service_rollout), - '__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_service_rollout(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = servicemanager.CreateServiceRolloutRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_create_service_rollout_async_from_dict(): - await test_create_service_rollout_async(request_type=dict) - -def test_create_service_rollout_field_headers(): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = servicemanager.CreateServiceRolloutRequest() - - request.service_name = 'service_name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_service_rollout), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_service_rollout(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'service_name=service_name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_create_service_rollout_field_headers_async(): - client = ServiceManagerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = servicemanager.CreateServiceRolloutRequest() - - request.service_name = 'service_name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_service_rollout), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.create_service_rollout(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', - 'service_name=service_name_value', - ) in kw['metadata'] - - -def test_create_service_rollout_flattened(): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_service_rollout), - '__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_service_rollout( - service_name='service_name_value', - rollout=resources.Rollout(rollout_id='rollout_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].service_name - mock_val = 'service_name_value' - assert arg == mock_val - arg = args[0].rollout - mock_val = resources.Rollout(rollout_id='rollout_id_value') - assert arg == mock_val - - -def test_create_service_rollout_flattened_error(): - client = ServiceManagerClient( - 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_service_rollout( - servicemanager.CreateServiceRolloutRequest(), - service_name='service_name_value', - rollout=resources.Rollout(rollout_id='rollout_id_value'), - ) - -@pytest.mark.asyncio -async def test_create_service_rollout_flattened_async(): - client = ServiceManagerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_service_rollout), - '__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_service_rollout( - service_name='service_name_value', - rollout=resources.Rollout(rollout_id='rollout_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].service_name - mock_val = 'service_name_value' - assert arg == mock_val - arg = args[0].rollout - mock_val = resources.Rollout(rollout_id='rollout_id_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_service_rollout_flattened_error_async(): - client = ServiceManagerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_service_rollout( - servicemanager.CreateServiceRolloutRequest(), - service_name='service_name_value', - rollout=resources.Rollout(rollout_id='rollout_id_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - servicemanager.GenerateConfigReportRequest, - dict, -]) -def test_generate_config_report(request_type, transport: str = 'grpc'): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_config_report), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = servicemanager.GenerateConfigReportResponse( - service_name='service_name_value', - id='id_value', - ) - response = client.generate_config_report(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = servicemanager.GenerateConfigReportRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, servicemanager.GenerateConfigReportResponse) - assert response.service_name == 'service_name_value' - assert response.id == 'id_value' - - -def test_generate_config_report_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = servicemanager.GenerateConfigReportRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_config_report), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.generate_config_report(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == servicemanager.GenerateConfigReportRequest( - ) - -def test_generate_config_report_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.generate_config_report in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.generate_config_report] = mock_rpc - request = {} - client.generate_config_report(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.generate_config_report(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_generate_config_report_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = ServiceManagerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.generate_config_report in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.generate_config_report] = mock_rpc - - request = {} - await client.generate_config_report(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.generate_config_report(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_generate_config_report_async(transport: str = 'grpc_asyncio', request_type=servicemanager.GenerateConfigReportRequest): - client = ServiceManagerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_config_report), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(servicemanager.GenerateConfigReportResponse( - service_name='service_name_value', - id='id_value', - )) - response = await client.generate_config_report(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = servicemanager.GenerateConfigReportRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, servicemanager.GenerateConfigReportResponse) - assert response.service_name == 'service_name_value' - assert response.id == 'id_value' - - -@pytest.mark.asyncio -async def test_generate_config_report_async_from_dict(): - await test_generate_config_report_async(request_type=dict) - - -def test_generate_config_report_flattened(): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_config_report), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = servicemanager.GenerateConfigReportResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.generate_config_report( - new_config=any_pb2.Any(type_url='type.googleapis.com/google.protobuf.Empty'), - old_config=any_pb2.Any(type_url='type.googleapis.com/google.protobuf.Empty'), - ) - - # 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].new_config - mock_val = any_pb2.Any(type_url='type.googleapis.com/google.protobuf.Empty') - assert arg == mock_val - arg = args[0].old_config - mock_val = any_pb2.Any(type_url='type.googleapis.com/google.protobuf.Empty') - assert arg == mock_val - - -def test_generate_config_report_flattened_error(): - client = ServiceManagerClient( - 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.generate_config_report( - servicemanager.GenerateConfigReportRequest(), - new_config=any_pb2.Any(type_url='type.googleapis.com/google.protobuf.Empty'), - old_config=any_pb2.Any(type_url='type.googleapis.com/google.protobuf.Empty'), - ) - -@pytest.mark.asyncio -async def test_generate_config_report_flattened_async(): - client = ServiceManagerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_config_report), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = servicemanager.GenerateConfigReportResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(servicemanager.GenerateConfigReportResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.generate_config_report( - new_config=any_pb2.Any(type_url='type.googleapis.com/google.protobuf.Empty'), - old_config=any_pb2.Any(type_url='type.googleapis.com/google.protobuf.Empty'), - ) - - # 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].new_config - mock_val = any_pb2.Any(type_url='type.googleapis.com/google.protobuf.Empty') - assert arg == mock_val - arg = args[0].old_config - mock_val = any_pb2.Any(type_url='type.googleapis.com/google.protobuf.Empty') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_generate_config_report_flattened_error_async(): - client = ServiceManagerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.generate_config_report( - servicemanager.GenerateConfigReportRequest(), - new_config=any_pb2.Any(type_url='type.googleapis.com/google.protobuf.Empty'), - old_config=any_pb2.Any(type_url='type.googleapis.com/google.protobuf.Empty'), - ) - - -def test_list_services_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_services in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_services] = mock_rpc - - request = {} - client.list_services(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_services(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_list_services_rest_flattened(): - client = ServiceManagerClient( - 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 = servicemanager.ListServicesResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {} - - # get truthy value for each flattened field - mock_args = dict( - producer_project_id='producer_project_id_value', - consumer_id='consumer_id_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = servicemanager.ListServicesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.list_services(**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/services" % client.transport._host, args[1]) - - -def test_list_services_rest_flattened_error(transport: str = 'rest'): - client = ServiceManagerClient( - 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_services( - servicemanager.ListServicesRequest(), - producer_project_id='producer_project_id_value', - consumer_id='consumer_id_value', - ) - - -def test_list_services_rest_pager(transport: str = 'rest'): - client = ServiceManagerClient( - 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 = ( - servicemanager.ListServicesResponse( - services=[ - resources.ManagedService(), - resources.ManagedService(), - resources.ManagedService(), - ], - next_page_token='abc', - ), - servicemanager.ListServicesResponse( - services=[], - next_page_token='def', - ), - servicemanager.ListServicesResponse( - services=[ - resources.ManagedService(), - ], - next_page_token='ghi', - ), - servicemanager.ListServicesResponse( - services=[ - resources.ManagedService(), - resources.ManagedService(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(servicemanager.ListServicesResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode('UTF-8') - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {} - - pager = client.list_services(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, resources.ManagedService) - for i in results) - - pages = list(client.list_services(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_get_service_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_service in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_service] = mock_rpc - - request = {} - client.get_service(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_service(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_get_service_rest_required_fields(request_type=servicemanager.GetServiceRequest): - transport_class = transports.ServiceManagerRestTransport - - request_init = {} - request_init["service_name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_service._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["serviceName"] = 'service_name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_service._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "serviceName" in jsonified_request - assert jsonified_request["serviceName"] == 'service_name_value' - - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = resources.ManagedService() - # Mock the http request call 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 = resources.ManagedService.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.get_service(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_service_rest_unset_required_fields(): - transport = transports.ServiceManagerRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_service._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("serviceName", ))) - - -def test_get_service_rest_flattened(): - client = ServiceManagerClient( - 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 = resources.ManagedService() - - # get arguments that satisfy an http rule for this method - sample_request = {'service_name': 'sample1'} - - # get truthy value for each flattened field - mock_args = dict( - service_name='service_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 = resources.ManagedService.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.get_service(**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/services/{service_name}" % client.transport._host, args[1]) - - -def test_get_service_rest_flattened_error(transport: str = 'rest'): - client = ServiceManagerClient( - 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_service( - servicemanager.GetServiceRequest(), - service_name='service_name_value', - ) - - -def test_create_service_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.create_service in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.create_service] = mock_rpc - - request = {} - client.create_service(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.create_service(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_create_service_rest_required_fields(request_type=servicemanager.CreateServiceRequest): - transport_class = transports.ServiceManagerRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_service._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()).create_service._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.create_service(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_service_rest_unset_required_fields(): - transport = transports.ServiceManagerRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_service._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("service", ))) - - -def test_create_service_rest_flattened(): - client = ServiceManagerClient( - 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 = {} - - # get truthy value for each flattened field - mock_args = dict( - service=resources.ManagedService(service_name='service_name_value'), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.create_service(**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/services" % client.transport._host, args[1]) - - -def test_create_service_rest_flattened_error(transport: str = 'rest'): - client = ServiceManagerClient( - 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_service( - servicemanager.CreateServiceRequest(), - service=resources.ManagedService(service_name='service_name_value'), - ) - - -def test_delete_service_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.delete_service in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.delete_service] = mock_rpc - - request = {} - client.delete_service(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.delete_service(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_delete_service_rest_required_fields(request_type=servicemanager.DeleteServiceRequest): - transport_class = transports.ServiceManagerRestTransport - - request_init = {} - request_init["service_name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_service._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["serviceName"] = 'service_name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_service._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "serviceName" in jsonified_request - assert jsonified_request["serviceName"] == 'service_name_value' - - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "delete", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.delete_service(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_service_rest_unset_required_fields(): - transport = transports.ServiceManagerRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_service._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("serviceName", ))) - - -def test_delete_service_rest_flattened(): - client = ServiceManagerClient( - 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 = {'service_name': 'sample1'} - - # get truthy value for each flattened field - mock_args = dict( - service_name='service_name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.delete_service(**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/services/{service_name}" % client.transport._host, args[1]) - - -def test_delete_service_rest_flattened_error(transport: str = 'rest'): - client = ServiceManagerClient( - 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_service( - servicemanager.DeleteServiceRequest(), - service_name='service_name_value', - ) - - -def test_undelete_service_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.undelete_service in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.undelete_service] = mock_rpc - - request = {} - client.undelete_service(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.undelete_service(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_undelete_service_rest_required_fields(request_type=servicemanager.UndeleteServiceRequest): - transport_class = transports.ServiceManagerRestTransport - - request_init = {} - request_init["service_name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).undelete_service._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["serviceName"] = 'service_name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).undelete_service._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "serviceName" in jsonified_request - assert jsonified_request["serviceName"] == 'service_name_value' - - client = ServiceManagerClient( - 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.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.undelete_service(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_undelete_service_rest_unset_required_fields(): - transport = transports.ServiceManagerRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.undelete_service._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("serviceName", ))) - - -def test_undelete_service_rest_flattened(): - client = ServiceManagerClient( - 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 = {'service_name': 'sample1'} - - # get truthy value for each flattened field - mock_args = dict( - service_name='service_name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.undelete_service(**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/services/{service_name}:undelete" % client.transport._host, args[1]) - - -def test_undelete_service_rest_flattened_error(transport: str = 'rest'): - client = ServiceManagerClient( - 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.undelete_service( - servicemanager.UndeleteServiceRequest(), - service_name='service_name_value', - ) - - -def test_list_service_configs_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_service_configs in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_service_configs] = mock_rpc - - request = {} - client.list_service_configs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_service_configs(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_list_service_configs_rest_required_fields(request_type=servicemanager.ListServiceConfigsRequest): - transport_class = transports.ServiceManagerRestTransport - - request_init = {} - request_init["service_name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_service_configs._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["serviceName"] = 'service_name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_service_configs._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "serviceName" in jsonified_request - assert jsonified_request["serviceName"] == 'service_name_value' - - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = servicemanager.ListServiceConfigsResponse() - # Mock the http request call 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 = servicemanager.ListServiceConfigsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.list_service_configs(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_service_configs_rest_unset_required_fields(): - transport = transports.ServiceManagerRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_service_configs._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("serviceName", ))) - - -def test_list_service_configs_rest_flattened(): - client = ServiceManagerClient( - 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 = servicemanager.ListServiceConfigsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'service_name': 'sample1'} - - # get truthy value for each flattened field - mock_args = dict( - service_name='service_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 = servicemanager.ListServiceConfigsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.list_service_configs(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/services/{service_name}/configs" % client.transport._host, args[1]) - - -def test_list_service_configs_rest_flattened_error(transport: str = 'rest'): - client = ServiceManagerClient( - 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_service_configs( - servicemanager.ListServiceConfigsRequest(), - service_name='service_name_value', - ) - - -def test_list_service_configs_rest_pager(transport: str = 'rest'): - client = ServiceManagerClient( - 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 = ( - servicemanager.ListServiceConfigsResponse( - service_configs=[ - service_pb2.Service(), - service_pb2.Service(), - service_pb2.Service(), - ], - next_page_token='abc', - ), - servicemanager.ListServiceConfigsResponse( - service_configs=[], - next_page_token='def', - ), - servicemanager.ListServiceConfigsResponse( - service_configs=[ - service_pb2.Service(), - ], - next_page_token='ghi', - ), - servicemanager.ListServiceConfigsResponse( - service_configs=[ - service_pb2.Service(), - service_pb2.Service(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(servicemanager.ListServiceConfigsResponse.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 = {'service_name': 'sample1'} - - pager = client.list_service_configs(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, service_pb2.Service) - for i in results) - - pages = list(client.list_service_configs(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_get_service_config_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_service_config in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_service_config] = mock_rpc - - request = {} - client.get_service_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_service_config(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_get_service_config_rest_required_fields(request_type=servicemanager.GetServiceConfigRequest): - transport_class = transports.ServiceManagerRestTransport - - request_init = {} - request_init["service_name"] = "" - request_init["config_id"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_service_config._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["serviceName"] = 'service_name_value' - jsonified_request["configId"] = 'config_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_service_config._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("view", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "serviceName" in jsonified_request - assert jsonified_request["serviceName"] == 'service_name_value' - assert "configId" in jsonified_request - assert jsonified_request["configId"] == 'config_id_value' - - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = service_pb2.Service() - # Mock the http request call 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 - - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.get_service_config(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_service_config_rest_unset_required_fields(): - transport = transports.ServiceManagerRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_service_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(("view", )) & set(("serviceName", "configId", ))) - - -def test_get_service_config_rest_flattened(): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = service_pb2.Service() - - # get arguments that satisfy an http rule for this method - sample_request = {'service_name': 'sample1', 'config_id': 'sample2'} - - # get truthy value for each flattened field - mock_args = dict( - service_name='service_name_value', - config_id='config_id_value', - view=servicemanager.GetServiceConfigRequest.ConfigView.FULL, - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.get_service_config(**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/services/{service_name}/configs/{config_id}" % client.transport._host, args[1]) - - -def test_get_service_config_rest_flattened_error(transport: str = 'rest'): - client = ServiceManagerClient( - 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_service_config( - servicemanager.GetServiceConfigRequest(), - service_name='service_name_value', - config_id='config_id_value', - view=servicemanager.GetServiceConfigRequest.ConfigView.FULL, - ) - - -def test_create_service_config_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.create_service_config in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.create_service_config] = mock_rpc - - request = {} - client.create_service_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_service_config(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_create_service_config_rest_required_fields(request_type=servicemanager.CreateServiceConfigRequest): - transport_class = transports.ServiceManagerRestTransport - - request_init = {} - request_init["service_name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_service_config._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["serviceName"] = 'service_name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_service_config._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "serviceName" in jsonified_request - assert jsonified_request["serviceName"] == 'service_name_value' - - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = service_pb2.Service() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.create_service_config(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_service_config_rest_unset_required_fields(): - transport = transports.ServiceManagerRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_service_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("serviceName", "serviceConfig", ))) - - -def test_create_service_config_rest_flattened(): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = service_pb2.Service() - - # get arguments that satisfy an http rule for this method - sample_request = {'service_name': 'sample1'} - - # get truthy value for each flattened field - mock_args = dict( - service_name='service_name_value', - service_config=service_pb2.Service(name='name_value'), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.create_service_config(**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/services/{service_name}/configs" % client.transport._host, args[1]) - - -def test_create_service_config_rest_flattened_error(transport: str = 'rest'): - client = ServiceManagerClient( - 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_service_config( - servicemanager.CreateServiceConfigRequest(), - service_name='service_name_value', - service_config=service_pb2.Service(name='name_value'), - ) - - -def test_submit_config_source_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.submit_config_source in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.submit_config_source] = mock_rpc - - request = {} - client.submit_config_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.submit_config_source(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_submit_config_source_rest_required_fields(request_type=servicemanager.SubmitConfigSourceRequest): - transport_class = transports.ServiceManagerRestTransport - - request_init = {} - request_init["service_name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).submit_config_source._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["serviceName"] = 'service_name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).submit_config_source._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "serviceName" in jsonified_request - assert jsonified_request["serviceName"] == 'service_name_value' - - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.submit_config_source(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_submit_config_source_rest_unset_required_fields(): - transport = transports.ServiceManagerRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.submit_config_source._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("serviceName", "configSource", ))) - - -def test_submit_config_source_rest_flattened(): - client = ServiceManagerClient( - 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 = {'service_name': 'sample1'} - - # get truthy value for each flattened field - mock_args = dict( - service_name='service_name_value', - config_source=resources.ConfigSource(id='id_value'), - validate_only=True, - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.submit_config_source(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/services/{service_name}/configs:submit" % client.transport._host, args[1]) - - -def test_submit_config_source_rest_flattened_error(transport: str = 'rest'): - client = ServiceManagerClient( - 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.submit_config_source( - servicemanager.SubmitConfigSourceRequest(), - service_name='service_name_value', - config_source=resources.ConfigSource(id='id_value'), - validate_only=True, - ) - - -def test_list_service_rollouts_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_service_rollouts in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_service_rollouts] = mock_rpc - - request = {} - client.list_service_rollouts(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_service_rollouts(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_list_service_rollouts_rest_required_fields(request_type=servicemanager.ListServiceRolloutsRequest): - transport_class = transports.ServiceManagerRestTransport - - request_init = {} - request_init["service_name"] = "" - request_init["filter"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - assert "filter" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_service_rollouts._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "filter" in jsonified_request - assert jsonified_request["filter"] == request_init["filter"] - - jsonified_request["serviceName"] = 'service_name_value' - jsonified_request["filter"] = 'filter_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_service_rollouts._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("filter", "page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "serviceName" in jsonified_request - assert jsonified_request["serviceName"] == 'service_name_value' - assert "filter" in jsonified_request - assert jsonified_request["filter"] == 'filter_value' - - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = servicemanager.ListServiceRolloutsResponse() - # Mock the http request call 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 = servicemanager.ListServiceRolloutsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.list_service_rollouts(request) - - expected_params = [ - ( - "filter", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_service_rollouts_rest_unset_required_fields(): - transport = transports.ServiceManagerRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_service_rollouts._get_unset_required_fields({}) - assert set(unset_fields) == (set(("filter", "pageSize", "pageToken", )) & set(("serviceName", "filter", ))) - - -def test_list_service_rollouts_rest_flattened(): - client = ServiceManagerClient( - 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 = servicemanager.ListServiceRolloutsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'service_name': 'sample1'} - - # get truthy value for each flattened field - mock_args = dict( - service_name='service_name_value', - filter='filter_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 = servicemanager.ListServiceRolloutsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.list_service_rollouts(**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/services/{service_name}/rollouts" % client.transport._host, args[1]) - - -def test_list_service_rollouts_rest_flattened_error(transport: str = 'rest'): - client = ServiceManagerClient( - 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_service_rollouts( - servicemanager.ListServiceRolloutsRequest(), - service_name='service_name_value', - filter='filter_value', - ) - - -def test_list_service_rollouts_rest_pager(transport: str = 'rest'): - client = ServiceManagerClient( - 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 = ( - servicemanager.ListServiceRolloutsResponse( - rollouts=[ - resources.Rollout(), - resources.Rollout(), - resources.Rollout(), - ], - next_page_token='abc', - ), - servicemanager.ListServiceRolloutsResponse( - rollouts=[], - next_page_token='def', - ), - servicemanager.ListServiceRolloutsResponse( - rollouts=[ - resources.Rollout(), - ], - next_page_token='ghi', - ), - servicemanager.ListServiceRolloutsResponse( - rollouts=[ - resources.Rollout(), - resources.Rollout(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(servicemanager.ListServiceRolloutsResponse.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 = {'service_name': 'sample1'} - - pager = client.list_service_rollouts(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, resources.Rollout) - for i in results) - - pages = list(client.list_service_rollouts(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_get_service_rollout_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_service_rollout in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_service_rollout] = mock_rpc - - request = {} - client.get_service_rollout(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_service_rollout(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_get_service_rollout_rest_required_fields(request_type=servicemanager.GetServiceRolloutRequest): - transport_class = transports.ServiceManagerRestTransport - - request_init = {} - request_init["service_name"] = "" - request_init["rollout_id"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_service_rollout._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["serviceName"] = 'service_name_value' - jsonified_request["rolloutId"] = 'rollout_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_service_rollout._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "serviceName" in jsonified_request - assert jsonified_request["serviceName"] == 'service_name_value' - assert "rolloutId" in jsonified_request - assert jsonified_request["rolloutId"] == 'rollout_id_value' - - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = resources.Rollout() - # Mock the http request call 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 = resources.Rollout.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.get_service_rollout(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_service_rollout_rest_unset_required_fields(): - transport = transports.ServiceManagerRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_service_rollout._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("serviceName", "rolloutId", ))) - - -def test_get_service_rollout_rest_flattened(): - client = ServiceManagerClient( - 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 = resources.Rollout() - - # get arguments that satisfy an http rule for this method - sample_request = {'service_name': 'sample1', 'rollout_id': 'sample2'} - - # get truthy value for each flattened field - mock_args = dict( - service_name='service_name_value', - rollout_id='rollout_id_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = resources.Rollout.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.get_service_rollout(**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/services/{service_name}/rollouts/{rollout_id}" % client.transport._host, args[1]) - - -def test_get_service_rollout_rest_flattened_error(transport: str = 'rest'): - client = ServiceManagerClient( - 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_service_rollout( - servicemanager.GetServiceRolloutRequest(), - service_name='service_name_value', - rollout_id='rollout_id_value', - ) - - -def test_create_service_rollout_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.create_service_rollout in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.create_service_rollout] = mock_rpc - - request = {} - client.create_service_rollout(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.create_service_rollout(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_create_service_rollout_rest_required_fields(request_type=servicemanager.CreateServiceRolloutRequest): - transport_class = transports.ServiceManagerRestTransport - - request_init = {} - request_init["service_name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_service_rollout._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["serviceName"] = 'service_name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_service_rollout._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "serviceName" in jsonified_request - assert jsonified_request["serviceName"] == 'service_name_value' - - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.create_service_rollout(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_service_rollout_rest_unset_required_fields(): - transport = transports.ServiceManagerRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_service_rollout._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("serviceName", "rollout", ))) - - -def test_create_service_rollout_rest_flattened(): - client = ServiceManagerClient( - 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 = {'service_name': 'sample1'} - - # get truthy value for each flattened field - mock_args = dict( - service_name='service_name_value', - rollout=resources.Rollout(rollout_id='rollout_id_value'), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.create_service_rollout(**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/services/{service_name}/rollouts" % client.transport._host, args[1]) - - -def test_create_service_rollout_rest_flattened_error(transport: str = 'rest'): - client = ServiceManagerClient( - 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_service_rollout( - servicemanager.CreateServiceRolloutRequest(), - service_name='service_name_value', - rollout=resources.Rollout(rollout_id='rollout_id_value'), - ) - - -def test_generate_config_report_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.generate_config_report in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.generate_config_report] = mock_rpc - - request = {} - client.generate_config_report(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.generate_config_report(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_generate_config_report_rest_required_fields(request_type=servicemanager.GenerateConfigReportRequest): - transport_class = transports.ServiceManagerRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).generate_config_report._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()).generate_config_report._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = servicemanager.GenerateConfigReportResponse() - # Mock the http request call 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 = servicemanager.GenerateConfigReportResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.generate_config_report(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_generate_config_report_rest_unset_required_fields(): - transport = transports.ServiceManagerRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.generate_config_report._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("newConfig", ))) - - -def test_generate_config_report_rest_flattened(): - client = ServiceManagerClient( - 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 = servicemanager.GenerateConfigReportResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {} - - # get truthy value for each flattened field - mock_args = dict( - new_config=any_pb2.Any(type_url='type.googleapis.com/google.protobuf.Empty'), - old_config=any_pb2.Any(type_url='type.googleapis.com/google.protobuf.Empty'), - ) - 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 = servicemanager.GenerateConfigReportResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.generate_config_report(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/services:generateConfigReport" % client.transport._host, args[1]) - - -def test_generate_config_report_rest_flattened_error(transport: str = 'rest'): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.generate_config_report( - servicemanager.GenerateConfigReportRequest(), - new_config=any_pb2.Any(type_url='type.googleapis.com/google.protobuf.Empty'), - old_config=any_pb2.Any(type_url='type.googleapis.com/google.protobuf.Empty'), - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.ServiceManagerGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.ServiceManagerGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ServiceManagerClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.ServiceManagerGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ServiceManagerClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ServiceManagerClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.ServiceManagerGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ServiceManagerClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.ServiceManagerGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = ServiceManagerClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.ServiceManagerGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.ServiceManagerGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.ServiceManagerGrpcTransport, - transports.ServiceManagerGrpcAsyncIOTransport, - transports.ServiceManagerRestTransport, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -def test_transport_kind_grpc(): - transport = ServiceManagerClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" - - -def test_initialize_client_w_grpc(): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc" - ) - assert client is not None - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_list_services_empty_call_grpc(): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_services), - '__call__') as call: - call.return_value = servicemanager.ListServicesResponse() - client.list_services(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = servicemanager.ListServicesRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_get_service_empty_call_grpc(): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_service), - '__call__') as call: - call.return_value = resources.ManagedService() - client.get_service(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = servicemanager.GetServiceRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_create_service_empty_call_grpc(): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_service), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_service(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = servicemanager.CreateServiceRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_delete_service_empty_call_grpc(): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_service), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_service(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = servicemanager.DeleteServiceRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_undelete_service_empty_call_grpc(): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.undelete_service), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.undelete_service(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = servicemanager.UndeleteServiceRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_list_service_configs_empty_call_grpc(): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_service_configs), - '__call__') as call: - call.return_value = servicemanager.ListServiceConfigsResponse() - client.list_service_configs(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = servicemanager.ListServiceConfigsRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_get_service_config_empty_call_grpc(): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_service_config), - '__call__') as call: - call.return_value = service_pb2.Service() - client.get_service_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = servicemanager.GetServiceConfigRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_create_service_config_empty_call_grpc(): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_service_config), - '__call__') as call: - call.return_value = service_pb2.Service() - client.create_service_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = servicemanager.CreateServiceConfigRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_submit_config_source_empty_call_grpc(): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.submit_config_source), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.submit_config_source(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = servicemanager.SubmitConfigSourceRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_list_service_rollouts_empty_call_grpc(): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_service_rollouts), - '__call__') as call: - call.return_value = servicemanager.ListServiceRolloutsResponse() - client.list_service_rollouts(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = servicemanager.ListServiceRolloutsRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_get_service_rollout_empty_call_grpc(): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_service_rollout), - '__call__') as call: - call.return_value = resources.Rollout() - client.get_service_rollout(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = servicemanager.GetServiceRolloutRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_create_service_rollout_empty_call_grpc(): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_service_rollout), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_service_rollout(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = servicemanager.CreateServiceRolloutRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_generate_config_report_empty_call_grpc(): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.generate_config_report), - '__call__') as call: - call.return_value = servicemanager.GenerateConfigReportResponse() - client.generate_config_report(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = servicemanager.GenerateConfigReportRequest() - - assert args[0] == request_msg - - -def test_transport_kind_grpc_asyncio(): - transport = ServiceManagerAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" - - -def test_initialize_client_w_grpc_asyncio(): - client = ServiceManagerAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio" - ) - assert client is not None - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_list_services_empty_call_grpc_asyncio(): - client = ServiceManagerAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_services), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(servicemanager.ListServicesResponse( - next_page_token='next_page_token_value', - )) - await client.list_services(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = servicemanager.ListServicesRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_get_service_empty_call_grpc_asyncio(): - client = ServiceManagerAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_service), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.ManagedService( - service_name='service_name_value', - producer_project_id='producer_project_id_value', - )) - await client.get_service(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = servicemanager.GetServiceRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_create_service_empty_call_grpc_asyncio(): - client = ServiceManagerAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_service), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - await client.create_service(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = servicemanager.CreateServiceRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_delete_service_empty_call_grpc_asyncio(): - client = ServiceManagerAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_service), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - await client.delete_service(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = servicemanager.DeleteServiceRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_undelete_service_empty_call_grpc_asyncio(): - client = ServiceManagerAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.undelete_service), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - await client.undelete_service(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = servicemanager.UndeleteServiceRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_list_service_configs_empty_call_grpc_asyncio(): - client = ServiceManagerAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_service_configs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(servicemanager.ListServiceConfigsResponse( - next_page_token='next_page_token_value', - )) - await client.list_service_configs(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = servicemanager.ListServiceConfigsRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_get_service_config_empty_call_grpc_asyncio(): - client = ServiceManagerAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_service_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service_pb2.Service( - name='name_value', - title='title_value', - producer_project_id='producer_project_id_value', - id='id_value', - )) - await client.get_service_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = servicemanager.GetServiceConfigRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_create_service_config_empty_call_grpc_asyncio(): - client = ServiceManagerAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_service_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service_pb2.Service( - name='name_value', - title='title_value', - producer_project_id='producer_project_id_value', - id='id_value', - )) - await client.create_service_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = servicemanager.CreateServiceConfigRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_submit_config_source_empty_call_grpc_asyncio(): - client = ServiceManagerAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.submit_config_source), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - await client.submit_config_source(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = servicemanager.SubmitConfigSourceRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_list_service_rollouts_empty_call_grpc_asyncio(): - client = ServiceManagerAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_service_rollouts), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(servicemanager.ListServiceRolloutsResponse( - next_page_token='next_page_token_value', - )) - await client.list_service_rollouts(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = servicemanager.ListServiceRolloutsRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_get_service_rollout_empty_call_grpc_asyncio(): - client = ServiceManagerAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_service_rollout), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Rollout( - rollout_id='rollout_id_value', - created_by='created_by_value', - status=resources.Rollout.RolloutStatus.IN_PROGRESS, - service_name='service_name_value', - )) - await client.get_service_rollout(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = servicemanager.GetServiceRolloutRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_create_service_rollout_empty_call_grpc_asyncio(): - client = ServiceManagerAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_service_rollout), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - await client.create_service_rollout(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = servicemanager.CreateServiceRolloutRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_generate_config_report_empty_call_grpc_asyncio(): - client = ServiceManagerAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.generate_config_report), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(servicemanager.GenerateConfigReportResponse( - service_name='service_name_value', - id='id_value', - )) - await client.generate_config_report(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = servicemanager.GenerateConfigReportRequest() - - assert args[0] == request_msg - - -def test_transport_kind_rest(): - transport = ServiceManagerClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" - - -def test_list_services_rest_bad_request(request_type=servicemanager.ListServicesRequest): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_services(request) - - -@pytest.mark.parametrize("request_type", [ - servicemanager.ListServicesRequest, - dict, -]) -def test_list_services_rest_call_success(request_type): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = servicemanager.ListServicesResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = servicemanager.ListServicesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.list_services(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListServicesPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_services_rest_interceptors(null_interceptor): - transport = transports.ServiceManagerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ServiceManagerRestInterceptor(), - ) - client = ServiceManagerClient(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.ServiceManagerRestInterceptor, "post_list_services") as post, \ - mock.patch.object(transports.ServiceManagerRestInterceptor, "pre_list_services") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = servicemanager.ListServicesRequest.pb(servicemanager.ListServicesRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = servicemanager.ListServicesResponse.to_json(servicemanager.ListServicesResponse()) - req.return_value.content = return_value - - request = servicemanager.ListServicesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = servicemanager.ListServicesResponse() - - client.list_services(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_service_rest_bad_request(request_type=servicemanager.GetServiceRequest): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'service_name': 'sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_service(request) - - -@pytest.mark.parametrize("request_type", [ - servicemanager.GetServiceRequest, - dict, -]) -def test_get_service_rest_call_success(request_type): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'service_name': '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 = resources.ManagedService( - service_name='service_name_value', - producer_project_id='producer_project_id_value', - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = resources.ManagedService.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.get_service(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.ManagedService) - assert response.service_name == 'service_name_value' - assert response.producer_project_id == 'producer_project_id_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_service_rest_interceptors(null_interceptor): - transport = transports.ServiceManagerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ServiceManagerRestInterceptor(), - ) - client = ServiceManagerClient(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.ServiceManagerRestInterceptor, "post_get_service") as post, \ - mock.patch.object(transports.ServiceManagerRestInterceptor, "pre_get_service") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = servicemanager.GetServiceRequest.pb(servicemanager.GetServiceRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = resources.ManagedService.to_json(resources.ManagedService()) - req.return_value.content = return_value - - request = servicemanager.GetServiceRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = resources.ManagedService() - - client.get_service(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_service_rest_bad_request(request_type=servicemanager.CreateServiceRequest): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.create_service(request) - - -@pytest.mark.parametrize("request_type", [ - servicemanager.CreateServiceRequest, - dict, -]) -def test_create_service_rest_call_success(request_type): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {} - request_init["service"] = {'service_name': 'service_name_value', 'producer_project_id': 'producer_project_id_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 = servicemanager.CreateServiceRequest.meta.fields["service"] - - 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["service"].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["service"][field])): - del request_init["service"][field][i][subfield] - else: - del request_init["service"][field][subfield] - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.create_service(request) - - # Establish that the response is the type that we expect. - json_return_value = json_format.MessageToJson(return_value) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_service_rest_interceptors(null_interceptor): - transport = transports.ServiceManagerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ServiceManagerRestInterceptor(), - ) - client = ServiceManagerClient(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.ServiceManagerRestInterceptor, "post_create_service") as post, \ - mock.patch.object(transports.ServiceManagerRestInterceptor, "pre_create_service") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = servicemanager.CreateServiceRequest.pb(servicemanager.CreateServiceRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = servicemanager.CreateServiceRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.create_service(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_service_rest_bad_request(request_type=servicemanager.DeleteServiceRequest): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'service_name': 'sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.delete_service(request) - - -@pytest.mark.parametrize("request_type", [ - servicemanager.DeleteServiceRequest, - dict, -]) -def test_delete_service_rest_call_success(request_type): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'service_name': 'sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.delete_service(request) - - # Establish that the response is the type that we expect. - json_return_value = json_format.MessageToJson(return_value) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_service_rest_interceptors(null_interceptor): - transport = transports.ServiceManagerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ServiceManagerRestInterceptor(), - ) - client = ServiceManagerClient(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.ServiceManagerRestInterceptor, "post_delete_service") as post, \ - mock.patch.object(transports.ServiceManagerRestInterceptor, "pre_delete_service") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = servicemanager.DeleteServiceRequest.pb(servicemanager.DeleteServiceRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = servicemanager.DeleteServiceRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.delete_service(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_undelete_service_rest_bad_request(request_type=servicemanager.UndeleteServiceRequest): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'service_name': 'sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.undelete_service(request) - - -@pytest.mark.parametrize("request_type", [ - servicemanager.UndeleteServiceRequest, - dict, -]) -def test_undelete_service_rest_call_success(request_type): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'service_name': 'sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.undelete_service(request) - - # Establish that the response is the type that we expect. - json_return_value = json_format.MessageToJson(return_value) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_undelete_service_rest_interceptors(null_interceptor): - transport = transports.ServiceManagerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ServiceManagerRestInterceptor(), - ) - client = ServiceManagerClient(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.ServiceManagerRestInterceptor, "post_undelete_service") as post, \ - mock.patch.object(transports.ServiceManagerRestInterceptor, "pre_undelete_service") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = servicemanager.UndeleteServiceRequest.pb(servicemanager.UndeleteServiceRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = servicemanager.UndeleteServiceRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.undelete_service(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_service_configs_rest_bad_request(request_type=servicemanager.ListServiceConfigsRequest): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'service_name': 'sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_service_configs(request) - - -@pytest.mark.parametrize("request_type", [ - servicemanager.ListServiceConfigsRequest, - dict, -]) -def test_list_service_configs_rest_call_success(request_type): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'service_name': '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 = servicemanager.ListServiceConfigsResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = servicemanager.ListServiceConfigsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.list_service_configs(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListServiceConfigsPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_service_configs_rest_interceptors(null_interceptor): - transport = transports.ServiceManagerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ServiceManagerRestInterceptor(), - ) - client = ServiceManagerClient(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.ServiceManagerRestInterceptor, "post_list_service_configs") as post, \ - mock.patch.object(transports.ServiceManagerRestInterceptor, "pre_list_service_configs") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = servicemanager.ListServiceConfigsRequest.pb(servicemanager.ListServiceConfigsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = servicemanager.ListServiceConfigsResponse.to_json(servicemanager.ListServiceConfigsResponse()) - req.return_value.content = return_value - - request = servicemanager.ListServiceConfigsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = servicemanager.ListServiceConfigsResponse() - - client.list_service_configs(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_service_config_rest_bad_request(request_type=servicemanager.GetServiceConfigRequest): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'service_name': 'sample1', 'config_id': 'sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_service_config(request) - - -@pytest.mark.parametrize("request_type", [ - servicemanager.GetServiceConfigRequest, - dict, -]) -def test_get_service_config_rest_call_success(request_type): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'service_name': 'sample1', 'config_id': 'sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = service_pb2.Service( - name='name_value', - title='title_value', - producer_project_id='producer_project_id_value', - id='id_value', - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.get_service_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, service_pb2.Service) - assert response.name == 'name_value' - assert response.title == 'title_value' - assert response.producer_project_id == 'producer_project_id_value' - assert response.id == 'id_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_service_config_rest_interceptors(null_interceptor): - transport = transports.ServiceManagerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ServiceManagerRestInterceptor(), - ) - client = ServiceManagerClient(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.ServiceManagerRestInterceptor, "post_get_service_config") as post, \ - mock.patch.object(transports.ServiceManagerRestInterceptor, "pre_get_service_config") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = servicemanager.GetServiceConfigRequest.pb(servicemanager.GetServiceConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = json_format.MessageToJson(service_pb2.Service()) - req.return_value.content = return_value - - request = servicemanager.GetServiceConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = service_pb2.Service() - - client.get_service_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_service_config_rest_bad_request(request_type=servicemanager.CreateServiceConfigRequest): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'service_name': 'sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.create_service_config(request) - - -@pytest.mark.parametrize("request_type", [ - servicemanager.CreateServiceConfigRequest, - dict, -]) -def test_create_service_config_rest_call_success(request_type): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'service_name': 'sample1'} - request_init["service_config"] = {'name': 'name_value', 'title': 'title_value', 'producer_project_id': 'producer_project_id_value', 'id': 'id_value', 'apis': [{'name': 'name_value', 'methods': [{'name': 'name_value', 'request_type_url': 'request_type_url_value', 'request_streaming': True, 'response_type_url': 'response_type_url_value', 'response_streaming': True, 'options': [{'name': 'name_value', 'value': {'type_url': 'type.googleapis.com/google.protobuf.Duration', 'value': b'\x08\x0c\x10\xdb\x07'}}], 'syntax': 1}], 'options': {}, 'version': 'version_value', 'source_context': {'file_name': 'file_name_value'}, 'mixins': [{'name': 'name_value', 'root': 'root_value'}], 'syntax': 1}], 'types': [{'name': 'name_value', 'fields': [{'kind': 1, 'cardinality': 1, 'number': 649, 'name': 'name_value', 'type_url': 'type.googleapis.com/google.protobuf.Empty', 'oneof_index': 1166, 'packed': True, 'options': {}, 'json_name': 'json_name_value', 'default_value': 'default_value_value'}], 'oneofs': ['oneofs_value1', 'oneofs_value2'], 'options': {}, 'source_context': {}, 'syntax': 1, 'edition': 'edition_value'}], 'enums': [{'name': 'name_value', 'enumvalue': [{'name': 'name_value', 'number': 649, 'options': {}}], 'options': {}, 'source_context': {}, 'syntax': 1, 'edition': 'edition_value'}], 'documentation': {'summary': 'summary_value', 'pages': [{'name': 'name_value', 'content': 'content_value', 'subpages': {}}], 'rules': [{'selector': 'selector_value', 'description': 'description_value', 'deprecation_description': 'deprecation_description_value'}], 'documentation_root_url': 'documentation_root_url_value', 'service_root_url': 'service_root_url_value', 'overview': 'overview_value'}, 'backend': {'rules': [{'selector': 'selector_value', 'address': 'address_value', 'deadline': 0.8220000000000001, 'min_deadline': 0.1241, 'operation_deadline': 0.1894, 'path_translation': 1, 'jwt_audience': 'jwt_audience_value', 'disable_auth': True, 'protocol': 'protocol_value', 'overrides_by_request_protocol': {}}]}, 'http': {'rules': [{'selector': 'selector_value', 'get': 'get_value', 'put': 'put_value', 'post': 'post_value', 'delete': 'delete_value', 'patch': 'patch_value', 'custom': {'kind': 'kind_value', 'path': 'path_value'}, 'body': 'body_value', 'response_body': 'response_body_value', 'additional_bindings': {}}], 'fully_decode_reserved_expansion': True}, 'quota': {'limits': [{'name': 'name_value', 'description': 'description_value', 'default_limit': 1379, 'max_limit': 964, 'free_tier': 949, 'duration': 'duration_value', 'metric': 'metric_value', 'unit': 'unit_value', 'values': {}, 'display_name': 'display_name_value'}], 'metric_rules': [{'selector': 'selector_value', 'metric_costs': {}}]}, 'authentication': {'rules': [{'selector': 'selector_value', 'oauth': {'canonical_scopes': 'canonical_scopes_value'}, 'allow_without_credential': True, 'requirements': [{'provider_id': 'provider_id_value', 'audiences': 'audiences_value'}]}], 'providers': [{'id': 'id_value', 'issuer': 'issuer_value', 'jwks_uri': 'jwks_uri_value', 'audiences': 'audiences_value', 'authorization_url': 'authorization_url_value', 'jwt_locations': [{'header': 'header_value', 'query': 'query_value', 'cookie': 'cookie_value', 'value_prefix': 'value_prefix_value'}]}]}, 'context': {'rules': [{'selector': 'selector_value', 'requested': ['requested_value1', 'requested_value2'], 'provided': ['provided_value1', 'provided_value2'], 'allowed_request_extensions': ['allowed_request_extensions_value1', 'allowed_request_extensions_value2'], 'allowed_response_extensions': ['allowed_response_extensions_value1', 'allowed_response_extensions_value2']}]}, 'usage': {'requirements': ['requirements_value1', 'requirements_value2'], 'rules': [{'selector': 'selector_value', 'allow_unregistered_calls': True, 'skip_service_control': True}], 'producer_notification_channel': 'producer_notification_channel_value'}, 'endpoints': [{'name': 'name_value', 'aliases': ['aliases_value1', 'aliases_value2'], 'target': 'target_value', 'allow_cors': True}], 'control': {'environment': 'environment_value', 'method_policies': [{'selector': 'selector_value', 'request_policies': [{'selector': 'selector_value', 'resource_permission': 'resource_permission_value', 'resource_type': 'resource_type_value'}]}]}, 'logs': [{'name': 'name_value', 'labels': [{'key': 'key_value', 'value_type': 1, 'description': 'description_value'}], 'description': 'description_value', 'display_name': 'display_name_value'}], 'metrics': [{'name': 'name_value', 'type': 'type_value', 'labels': {}, 'metric_kind': 1, 'value_type': 1, 'unit': 'unit_value', 'description': 'description_value', 'display_name': 'display_name_value', 'metadata': {'launch_stage': 6, 'sample_period': {'seconds': 751, 'nanos': 543}, 'ingest_delay': {}, 'time_series_resource_hierarchy_level': [1]}, 'launch_stage': 6, 'monitored_resource_types': ['monitored_resource_types_value1', 'monitored_resource_types_value2']}], 'monitored_resources': [{'name': 'name_value', 'type': 'type_value', 'display_name': 'display_name_value', 'description': 'description_value', 'labels': {}, 'launch_stage': 6}], 'billing': {'consumer_destinations': [{'monitored_resource': 'monitored_resource_value', 'metrics': ['metrics_value1', 'metrics_value2']}]}, 'logging': {'producer_destinations': [{'monitored_resource': 'monitored_resource_value', 'logs': ['logs_value1', 'logs_value2']}], 'consumer_destinations': {}}, 'monitoring': {'producer_destinations': [{'monitored_resource': 'monitored_resource_value', 'metrics': ['metrics_value1', 'metrics_value2']}], 'consumer_destinations': {}}, 'system_parameters': {'rules': [{'selector': 'selector_value', 'parameters': [{'name': 'name_value', 'http_header': 'http_header_value', 'url_query_parameter': 'url_query_parameter_value'}]}]}, 'source_info': {'source_files': {}}, 'publishing': {'method_settings': [{'selector': 'selector_value', 'long_running': {'initial_poll_delay': {}, 'poll_delay_multiplier': 0.22510000000000002, 'max_poll_delay': {}, 'total_poll_timeout': {}}, 'auto_populated_fields': ['auto_populated_fields_value1', 'auto_populated_fields_value2']}], 'new_issue_uri': 'new_issue_uri_value', 'documentation_uri': 'documentation_uri_value', 'api_short_name': 'api_short_name_value', 'github_label': 'github_label_value', 'codeowner_github_teams': ['codeowner_github_teams_value1', 'codeowner_github_teams_value2'], 'doc_tag_prefix': 'doc_tag_prefix_value', 'organization': 1, 'library_settings': [{'version': 'version_value', 'launch_stage': 6, 'rest_numeric_enums': True, 'java_settings': {'library_package': 'library_package_value', 'service_class_names': {}, 'common': {'reference_docs_uri': 'reference_docs_uri_value', 'destinations': [10], 'selective_gapic_generation': {'methods': ['methods_value1', 'methods_value2']}}}, 'cpp_settings': {'common': {}}, 'php_settings': {'common': {}}, 'python_settings': {'common': {}, 'experimental_features': {'rest_async_io_enabled': True, 'protobuf_pythonic_types_enabled': True}}, 'node_settings': {'common': {}}, 'dotnet_settings': {'common': {}, 'renamed_services': {}, 'renamed_resources': {}, 'ignored_resources': ['ignored_resources_value1', 'ignored_resources_value2'], 'forced_namespace_aliases': ['forced_namespace_aliases_value1', 'forced_namespace_aliases_value2'], 'handwritten_signatures': ['handwritten_signatures_value1', 'handwritten_signatures_value2']}, 'ruby_settings': {'common': {}}, 'go_settings': {'common': {}, 'renamed_services': {}}}], 'proto_reference_documentation_uri': 'proto_reference_documentation_uri_value', 'rest_reference_documentation_uri': 'rest_reference_documentation_uri_value'}, 'config_version': {'value': 541}} - # 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 = servicemanager.CreateServiceConfigRequest.meta.fields["service_config"] - - 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["service_config"].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["service_config"][field])): - del request_init["service_config"][field][i][subfield] - else: - del request_init["service_config"][field][subfield] - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = service_pb2.Service( - name='name_value', - title='title_value', - producer_project_id='producer_project_id_value', - id='id_value', - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.create_service_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, service_pb2.Service) - assert response.name == 'name_value' - assert response.title == 'title_value' - assert response.producer_project_id == 'producer_project_id_value' - assert response.id == 'id_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_service_config_rest_interceptors(null_interceptor): - transport = transports.ServiceManagerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ServiceManagerRestInterceptor(), - ) - client = ServiceManagerClient(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.ServiceManagerRestInterceptor, "post_create_service_config") as post, \ - mock.patch.object(transports.ServiceManagerRestInterceptor, "pre_create_service_config") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = servicemanager.CreateServiceConfigRequest.pb(servicemanager.CreateServiceConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = json_format.MessageToJson(service_pb2.Service()) - req.return_value.content = return_value - - request = servicemanager.CreateServiceConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = service_pb2.Service() - - client.create_service_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_submit_config_source_rest_bad_request(request_type=servicemanager.SubmitConfigSourceRequest): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'service_name': 'sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.submit_config_source(request) - - -@pytest.mark.parametrize("request_type", [ - servicemanager.SubmitConfigSourceRequest, - dict, -]) -def test_submit_config_source_rest_call_success(request_type): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'service_name': 'sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.submit_config_source(request) - - # Establish that the response is the type that we expect. - json_return_value = json_format.MessageToJson(return_value) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_submit_config_source_rest_interceptors(null_interceptor): - transport = transports.ServiceManagerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ServiceManagerRestInterceptor(), - ) - client = ServiceManagerClient(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.ServiceManagerRestInterceptor, "post_submit_config_source") as post, \ - mock.patch.object(transports.ServiceManagerRestInterceptor, "pre_submit_config_source") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = servicemanager.SubmitConfigSourceRequest.pb(servicemanager.SubmitConfigSourceRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = servicemanager.SubmitConfigSourceRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.submit_config_source(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_service_rollouts_rest_bad_request(request_type=servicemanager.ListServiceRolloutsRequest): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'service_name': 'sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_service_rollouts(request) - - -@pytest.mark.parametrize("request_type", [ - servicemanager.ListServiceRolloutsRequest, - dict, -]) -def test_list_service_rollouts_rest_call_success(request_type): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'service_name': '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 = servicemanager.ListServiceRolloutsResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = servicemanager.ListServiceRolloutsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.list_service_rollouts(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListServiceRolloutsPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_service_rollouts_rest_interceptors(null_interceptor): - transport = transports.ServiceManagerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ServiceManagerRestInterceptor(), - ) - client = ServiceManagerClient(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.ServiceManagerRestInterceptor, "post_list_service_rollouts") as post, \ - mock.patch.object(transports.ServiceManagerRestInterceptor, "pre_list_service_rollouts") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = servicemanager.ListServiceRolloutsRequest.pb(servicemanager.ListServiceRolloutsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = servicemanager.ListServiceRolloutsResponse.to_json(servicemanager.ListServiceRolloutsResponse()) - req.return_value.content = return_value - - request = servicemanager.ListServiceRolloutsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = servicemanager.ListServiceRolloutsResponse() - - client.list_service_rollouts(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_service_rollout_rest_bad_request(request_type=servicemanager.GetServiceRolloutRequest): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'service_name': 'sample1', 'rollout_id': 'sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_service_rollout(request) - - -@pytest.mark.parametrize("request_type", [ - servicemanager.GetServiceRolloutRequest, - dict, -]) -def test_get_service_rollout_rest_call_success(request_type): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'service_name': 'sample1', 'rollout_id': '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 = resources.Rollout( - rollout_id='rollout_id_value', - created_by='created_by_value', - status=resources.Rollout.RolloutStatus.IN_PROGRESS, - service_name='service_name_value', - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = resources.Rollout.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.get_service_rollout(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.Rollout) - assert response.rollout_id == 'rollout_id_value' - assert response.created_by == 'created_by_value' - assert response.status == resources.Rollout.RolloutStatus.IN_PROGRESS - assert response.service_name == 'service_name_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_service_rollout_rest_interceptors(null_interceptor): - transport = transports.ServiceManagerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ServiceManagerRestInterceptor(), - ) - client = ServiceManagerClient(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.ServiceManagerRestInterceptor, "post_get_service_rollout") as post, \ - mock.patch.object(transports.ServiceManagerRestInterceptor, "pre_get_service_rollout") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = servicemanager.GetServiceRolloutRequest.pb(servicemanager.GetServiceRolloutRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = resources.Rollout.to_json(resources.Rollout()) - req.return_value.content = return_value - - request = servicemanager.GetServiceRolloutRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = resources.Rollout() - - client.get_service_rollout(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_service_rollout_rest_bad_request(request_type=servicemanager.CreateServiceRolloutRequest): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'service_name': 'sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.create_service_rollout(request) - - -@pytest.mark.parametrize("request_type", [ - servicemanager.CreateServiceRolloutRequest, - dict, -]) -def test_create_service_rollout_rest_call_success(request_type): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'service_name': 'sample1'} - request_init["rollout"] = {'rollout_id': 'rollout_id_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'created_by': 'created_by_value', 'status': 1, 'traffic_percent_strategy': {'percentages': {}}, 'delete_service_strategy': {}, 'service_name': 'service_name_value'} - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = servicemanager.CreateServiceRolloutRequest.meta.fields["rollout"] - - 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["rollout"].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["rollout"][field])): - del request_init["rollout"][field][i][subfield] - else: - del request_init["rollout"][field][subfield] - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.create_service_rollout(request) - - # Establish that the response is the type that we expect. - json_return_value = json_format.MessageToJson(return_value) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_service_rollout_rest_interceptors(null_interceptor): - transport = transports.ServiceManagerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ServiceManagerRestInterceptor(), - ) - client = ServiceManagerClient(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.ServiceManagerRestInterceptor, "post_create_service_rollout") as post, \ - mock.patch.object(transports.ServiceManagerRestInterceptor, "pre_create_service_rollout") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = servicemanager.CreateServiceRolloutRequest.pb(servicemanager.CreateServiceRolloutRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = servicemanager.CreateServiceRolloutRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.create_service_rollout(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_generate_config_report_rest_bad_request(request_type=servicemanager.GenerateConfigReportRequest): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.generate_config_report(request) - - -@pytest.mark.parametrize("request_type", [ - servicemanager.GenerateConfigReportRequest, - dict, -]) -def test_generate_config_report_rest_call_success(request_type): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = servicemanager.GenerateConfigReportResponse( - service_name='service_name_value', - id='id_value', - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = servicemanager.GenerateConfigReportResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.generate_config_report(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, servicemanager.GenerateConfigReportResponse) - assert response.service_name == 'service_name_value' - assert response.id == 'id_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_generate_config_report_rest_interceptors(null_interceptor): - transport = transports.ServiceManagerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ServiceManagerRestInterceptor(), - ) - client = ServiceManagerClient(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.ServiceManagerRestInterceptor, "post_generate_config_report") as post, \ - mock.patch.object(transports.ServiceManagerRestInterceptor, "pre_generate_config_report") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = servicemanager.GenerateConfigReportRequest.pb(servicemanager.GenerateConfigReportRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = servicemanager.GenerateConfigReportResponse.to_json(servicemanager.GenerateConfigReportResponse()) - req.return_value.content = return_value - - request = servicemanager.GenerateConfigReportRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = servicemanager.GenerateConfigReportResponse() - - client.generate_config_report(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_iam_policy_rest_bad_request(request_type=iam_policy_pb2.GetIamPolicyRequest): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'resource': 'services/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_iam_policy(request) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.GetIamPolicyRequest, - dict, -]) -def test_get_iam_policy_rest(request_type): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'resource': 'services/sample1'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.get_iam_policy(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - - -def test_set_iam_policy_rest_bad_request(request_type=iam_policy_pb2.SetIamPolicyRequest): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'resource': 'services/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.set_iam_policy(request) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.SetIamPolicyRequest, - dict, -]) -def test_set_iam_policy_rest(request_type): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'resource': 'services/sample1'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.set_iam_policy(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - - -def test_test_iam_permissions_rest_bad_request(request_type=iam_policy_pb2.TestIamPermissionsRequest): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'resource': 'services/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.test_iam_permissions(request) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.TestIamPermissionsRequest, - dict, -]) -def test_test_iam_permissions_rest(request_type): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'resource': 'services/sample1'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # Designate an appropriate value for the returned response. - return_value = iam_policy_pb2.TestIamPermissionsResponse() - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.test_iam_permissions(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) - - -def test_list_operations_rest_bad_request(request_type=operations_pb2.ListOperationsRequest): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_operations(request) - - -@pytest.mark.parametrize("request_type", [ - operations_pb2.ListOperationsRequest, - dict, -]) -def test_list_operations_rest(request_type): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - -def test_initialize_client_w_rest(): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - assert client is not None - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_list_services_empty_call_rest(): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_services), - '__call__') as call: - client.list_services(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = servicemanager.ListServicesRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_get_service_empty_call_rest(): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_service), - '__call__') as call: - client.get_service(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = servicemanager.GetServiceRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_create_service_empty_call_rest(): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_service), - '__call__') as call: - client.create_service(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = servicemanager.CreateServiceRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_delete_service_empty_call_rest(): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_service), - '__call__') as call: - client.delete_service(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = servicemanager.DeleteServiceRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_undelete_service_empty_call_rest(): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.undelete_service), - '__call__') as call: - client.undelete_service(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = servicemanager.UndeleteServiceRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_list_service_configs_empty_call_rest(): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_service_configs), - '__call__') as call: - client.list_service_configs(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = servicemanager.ListServiceConfigsRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_get_service_config_empty_call_rest(): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_service_config), - '__call__') as call: - client.get_service_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = servicemanager.GetServiceConfigRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_create_service_config_empty_call_rest(): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_service_config), - '__call__') as call: - client.create_service_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = servicemanager.CreateServiceConfigRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_submit_config_source_empty_call_rest(): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.submit_config_source), - '__call__') as call: - client.submit_config_source(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = servicemanager.SubmitConfigSourceRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_list_service_rollouts_empty_call_rest(): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_service_rollouts), - '__call__') as call: - client.list_service_rollouts(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = servicemanager.ListServiceRolloutsRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_get_service_rollout_empty_call_rest(): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_service_rollout), - '__call__') as call: - client.get_service_rollout(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = servicemanager.GetServiceRolloutRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_create_service_rollout_empty_call_rest(): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_service_rollout), - '__call__') as call: - client.create_service_rollout(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = servicemanager.CreateServiceRolloutRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_generate_config_report_empty_call_rest(): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.generate_config_report), - '__call__') as call: - client.generate_config_report(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = servicemanager.GenerateConfigReportRequest() - - assert args[0] == request_msg - - -def test_service_manager_rest_lro_client(): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - transport = client.transport - - # Ensure that we have an api-core operations client. - assert isinstance( - transport.operations_client, -operations_v1.AbstractOperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.ServiceManagerGrpcTransport, - ) - -def test_service_manager_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.ServiceManagerTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_service_manager_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.servicemanagement_v1.services.service_manager.transports.ServiceManagerTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.ServiceManagerTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'list_services', - 'get_service', - 'create_service', - 'delete_service', - 'undelete_service', - 'list_service_configs', - 'get_service_config', - 'create_service_config', - 'submit_config_source', - 'list_service_rollouts', - 'get_service_rollout', - 'create_service_rollout', - 'generate_config_report', - 'set_iam_policy', - 'get_iam_policy', - 'test_iam_permissions', - '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_service_manager_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.servicemanagement_v1.services.service_manager.transports.ServiceManagerTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ServiceManagerTransport( - 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', - 'https://www.googleapis.com/auth/cloud-platform.read-only', - 'https://www.googleapis.com/auth/service.management', - 'https://www.googleapis.com/auth/service.management.readonly', -), - quota_project_id="octopus", - ) - - -def test_service_manager_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.servicemanagement_v1.services.service_manager.transports.ServiceManagerTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ServiceManagerTransport() - adc.assert_called_once() - - -def test_service_manager_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) - ServiceManagerClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', - 'https://www.googleapis.com/auth/service.management', - 'https://www.googleapis.com/auth/service.management.readonly', -), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.ServiceManagerGrpcTransport, - transports.ServiceManagerGrpcAsyncIOTransport, - ], -) -def test_service_manager_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', 'https://www.googleapis.com/auth/cloud-platform.read-only', 'https://www.googleapis.com/auth/service.management', 'https://www.googleapis.com/auth/service.management.readonly',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.ServiceManagerGrpcTransport, - transports.ServiceManagerGrpcAsyncIOTransport, - transports.ServiceManagerRestTransport, - ], -) -def test_service_manager_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.ServiceManagerGrpcTransport, grpc_helpers), - (transports.ServiceManagerGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_service_manager_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( - "servicemanagement.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', - 'https://www.googleapis.com/auth/service.management', - 'https://www.googleapis.com/auth/service.management.readonly', -), - scopes=["1", "2"], - default_host="servicemanagement.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.ServiceManagerGrpcTransport, transports.ServiceManagerGrpcAsyncIOTransport]) -def test_service_manager_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_service_manager_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.ServiceManagerRestTransport ( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_service_manager_host_no_port(transport_name): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='servicemanagement.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'servicemanagement.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://servicemanagement.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_service_manager_host_with_port(transport_name): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='servicemanagement.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'servicemanagement.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://servicemanagement.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_service_manager_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = ServiceManagerClient( - credentials=creds1, - transport=transport_name, - ) - client2 = ServiceManagerClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.list_services._session - session2 = client2.transport.list_services._session - assert session1 != session2 - session1 = client1.transport.get_service._session - session2 = client2.transport.get_service._session - assert session1 != session2 - session1 = client1.transport.create_service._session - session2 = client2.transport.create_service._session - assert session1 != session2 - session1 = client1.transport.delete_service._session - session2 = client2.transport.delete_service._session - assert session1 != session2 - session1 = client1.transport.undelete_service._session - session2 = client2.transport.undelete_service._session - assert session1 != session2 - session1 = client1.transport.list_service_configs._session - session2 = client2.transport.list_service_configs._session - assert session1 != session2 - session1 = client1.transport.get_service_config._session - session2 = client2.transport.get_service_config._session - assert session1 != session2 - session1 = client1.transport.create_service_config._session - session2 = client2.transport.create_service_config._session - assert session1 != session2 - session1 = client1.transport.submit_config_source._session - session2 = client2.transport.submit_config_source._session - assert session1 != session2 - session1 = client1.transport.list_service_rollouts._session - session2 = client2.transport.list_service_rollouts._session - assert session1 != session2 - session1 = client1.transport.get_service_rollout._session - session2 = client2.transport.get_service_rollout._session - assert session1 != session2 - session1 = client1.transport.create_service_rollout._session - session2 = client2.transport.create_service_rollout._session - assert session1 != session2 - session1 = client1.transport.generate_config_report._session - session2 = client2.transport.generate_config_report._session - assert session1 != session2 -def test_service_manager_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ServiceManagerGrpcTransport( - 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_service_manager_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ServiceManagerGrpcAsyncIOTransport( - 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.ServiceManagerGrpcTransport, transports.ServiceManagerGrpcAsyncIOTransport]) -def test_service_manager_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.ServiceManagerGrpcTransport, transports.ServiceManagerGrpcAsyncIOTransport]) -def test_service_manager_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_service_manager_grpc_lro_client(): - client = ServiceManagerClient( - 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_service_manager_grpc_lro_async_client(): - client = ServiceManagerAsyncClient( - 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_common_billing_account_path(): - billing_account = "squid" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = ServiceManagerClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "clam", - } - path = ServiceManagerClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = ServiceManagerClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "whelk" - expected = "folders/{folder}".format(folder=folder, ) - actual = ServiceManagerClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "octopus", - } - path = ServiceManagerClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = ServiceManagerClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "oyster" - expected = "organizations/{organization}".format(organization=organization, ) - actual = ServiceManagerClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nudibranch", - } - path = ServiceManagerClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = ServiceManagerClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "cuttlefish" - expected = "projects/{project}".format(project=project, ) - actual = ServiceManagerClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "mussel", - } - path = ServiceManagerClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = ServiceManagerClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "winkle" - location = "nautilus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = ServiceManagerClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "scallop", - "location": "abalone", - } - path = ServiceManagerClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = ServiceManagerClient.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.ServiceManagerTransport, '_prep_wrapped_messages') as prep: - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.ServiceManagerTransport, '_prep_wrapped_messages') as prep: - transport_class = ServiceManagerClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - -def test_list_operations(transport: str = "grpc"): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = ServiceManagerAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.ListOperationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - -def test_list_operations_field_headers(): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = ServiceManagerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = operations_pb2.ListOperationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - await client.list_operations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] - -def test_list_operations_from_dict(): - client = ServiceManagerClient( - 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 = ServiceManagerAsyncClient( - credentials=async_anonymous_credentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_set_iam_policy(transport: str = "grpc"): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = ServiceManagerAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = iam_policy_pb2.SetIamPolicyRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy(version=774, etag=b"etag_blob",) - ) - response = await client.set_iam_policy(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - - assert response.version == 774 - - assert response.etag == b"etag_blob" - -def test_set_iam_policy_field_headers(): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = ServiceManagerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.SetIamPolicyRequest() - request.resource = "resource/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) - - await client.set_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] - -def test_set_iam_policy_from_dict(): - client = ServiceManagerClient( - 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 = ServiceManagerAsyncClient( - credentials=async_anonymous_credentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy() - ) - - response = await client.set_iam_policy( - request={ - "resource": "resource_value", - "policy": policy_pb2.Policy(version=774), - } - ) - call.assert_called() - -def test_get_iam_policy(transport: str = "grpc"): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = ServiceManagerAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = iam_policy_pb2.GetIamPolicyRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_iam_policy), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy(version=774, etag=b"etag_blob",) - ) - - response = await client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - - assert response.version == 774 - - assert response.etag == b"etag_blob" - - -def test_get_iam_policy_field_headers(): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = ServiceManagerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.GetIamPolicyRequest() - request.resource = "resource/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_iam_policy), "__call__" - ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) - - await client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] - - -def test_get_iam_policy_from_dict(): - client = ServiceManagerClient( - 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 = ServiceManagerAsyncClient( - credentials=async_anonymous_credentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy() - ) - - response = await client.get_iam_policy( - request={ - "resource": "resource_value", - "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), - } - ) - call.assert_called() - -def test_test_iam_permissions(transport: str = "grpc"): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = ServiceManagerAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = iam_policy_pb2.TestIamPermissionsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy_pb2.TestIamPermissionsResponse(permissions=["permissions_value"],) - ) - - response = await client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) - - assert response.permissions == ["permissions_value"] - - -def test_test_iam_permissions_field_headers(): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = ServiceManagerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.TestIamPermissionsRequest() - request.resource = "resource/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy_pb2.TestIamPermissionsResponse() - ) - - await client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] - - -def test_test_iam_permissions_from_dict(): - client = ServiceManagerClient( - 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 = ServiceManagerAsyncClient( - credentials=async_anonymous_credentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy_pb2.TestIamPermissionsResponse() - ) - - response = await client.test_iam_permissions( - request={ - "resource": "resource_value", - "permissions": ["permissions_value"], - } - ) - call.assert_called() - - -def test_transport_close_grpc(): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc" - ) - with mock.patch.object(type(getattr(client.transport, "_grpc_channel")), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - - -@pytest.mark.asyncio -async def test_transport_close_grpc_asyncio(): - client = ServiceManagerAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio" - ) - with mock.patch.object(type(getattr(client.transport, "_grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_transport_close_rest(): - client = ServiceManagerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - with mock.patch.object(type(getattr(client.transport, "_session")), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - - -def test_client_ctx(): - transports = [ - 'rest', - 'grpc', - ] - for transport in transports: - client = ServiceManagerClient( - 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", [ - (ServiceManagerClient, transports.ServiceManagerGrpcTransport), - (ServiceManagerAsyncClient, transports.ServiceManagerGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/packages/google-cloud-service-management/google/cloud/servicemanagement_v1/services/service_manager/async_client.py b/packages/google-cloud-service-management/google/cloud/servicemanagement_v1/services/service_manager/async_client.py index f715c89a98d4..b2682a175589 100644 --- a/packages/google-cloud-service-management/google/cloud/servicemanagement_v1/services/service_manager/async_client.py +++ b/packages/google-cloud-service-management/google/cloud/servicemanagement_v1/services/service_manager/async_client.py @@ -14,6 +14,7 @@ # limitations under the License. # from collections import OrderedDict +import logging as std_logging import re from typing import ( Callable, @@ -80,6 +81,15 @@ from .transports.base import DEFAULT_CLIENT_INFO, ServiceManagerTransport from .transports.grpc_asyncio import ServiceManagerGrpcAsyncIOTransport +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + class ServiceManagerAsyncClient: """`Google Service Management @@ -285,6 +295,28 @@ def __init__( client_info=client_info, ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.api.servicemanagement_v1.ServiceManagerAsyncClient`.", + extra={ + "serviceName": "google.api.servicemanagement.v1.ServiceManager", + "universeDomain": getattr( + self._client._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._client._transport, "_credentials") + else { + "serviceName": "google.api.servicemanagement.v1.ServiceManager", + "credentialsType": None, + }, + ) + async def list_services( self, request: Optional[Union[servicemanager.ListServicesRequest, dict]] = None, @@ -293,7 +325,7 @@ async def list_services( consumer_id: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> pagers.ListServicesAsyncPager: r"""Lists managed services. @@ -351,8 +383,10 @@ async def sample_list_services(): retry (google.api_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. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.cloud.servicemanagement_v1.services.service_manager.pagers.ListServicesAsyncPager: @@ -422,7 +456,7 @@ async def get_service( service_name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> resources.ManagedService: r"""Gets a managed service. Authentication is required unless the service is public. @@ -467,8 +501,10 @@ async def sample_get_service(): retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.cloud.servicemanagement_v1.types.ManagedService: @@ -532,7 +568,7 @@ async def create_service( service: Optional[resources.ManagedService] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operation_async.AsyncOperation: r"""Creates a new managed service. @@ -590,8 +626,10 @@ async def sample_create_service(): retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.api_core.operation_async.AsyncOperation: @@ -656,7 +694,7 @@ async def delete_service( service_name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operation_async.AsyncOperation: r"""Deletes a managed service. This method will change the service to the ``Soft-Delete`` state for 30 days. Within this period, @@ -713,8 +751,10 @@ async def sample_delete_service(): retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.api_core.operation_async.AsyncOperation: @@ -795,7 +835,7 @@ async def undelete_service( service_name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operation_async.AsyncOperation: r"""Revives a previously deleted managed service. The method restores the service using the configuration at @@ -851,8 +891,10 @@ async def sample_undelete_service(): retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.api_core.operation_async.AsyncOperation: @@ -926,7 +968,7 @@ async def list_service_configs( service_name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> pagers.ListServiceConfigsAsyncPager: r"""Lists the history of the service configuration for a managed service, from the newest to the oldest. @@ -974,8 +1016,10 @@ async def sample_list_service_configs(): retry (google.api_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. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.cloud.servicemanagement_v1.services.service_manager.pagers.ListServiceConfigsAsyncPager: @@ -1054,7 +1098,7 @@ async def get_service_config( view: Optional[servicemanager.GetServiceConfigRequest.ConfigView] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> service_pb2.Service: r"""Gets a service configuration (version) for a managed service. @@ -1119,8 +1163,10 @@ async def sample_get_service_config(): retry (google.api_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. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.api.service_pb2.Service: @@ -1220,7 +1266,7 @@ async def create_service_config( service_config: Optional[service_pb2.Service] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> service_pb2.Service: r"""Creates a new service configuration (version) for a managed service. This method only stores the service configuration. To @@ -1281,8 +1327,10 @@ async def sample_create_service_config(): retry (google.api_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. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.api.service_pb2.Service: @@ -1376,7 +1424,7 @@ async def submit_config_source( validate_only: Optional[bool] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operation_async.AsyncOperation: r"""Creates a new service configuration (version) for a managed service based on user-supplied configuration source files (for @@ -1454,8 +1502,10 @@ async def sample_submit_config_source(): retry (google.api_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. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.api_core.operation_async.AsyncOperation: @@ -1536,7 +1586,7 @@ async def list_service_rollouts( filter: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> pagers.ListServiceRolloutsAsyncPager: r"""Lists the history of the service configuration rollouts for a managed service, from the newest to the @@ -1601,8 +1651,10 @@ async def sample_list_service_rollouts(): retry (google.api_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. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.cloud.servicemanagement_v1.services.service_manager.pagers.ListServiceRolloutsAsyncPager: @@ -1682,7 +1734,7 @@ async def get_service_rollout( rollout_id: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> resources.Rollout: r"""Gets a service configuration [rollout][google.api.servicemanagement.v1.Rollout]. @@ -1737,8 +1789,10 @@ async def sample_get_service_rollout(): retry (google.api_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. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.cloud.servicemanagement_v1.types.Rollout: @@ -1813,7 +1867,7 @@ async def create_service_rollout( rollout: Optional[resources.Rollout] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operation_async.AsyncOperation: r"""Creates a new service configuration rollout. Based on rollout, the Google Service Management will roll out the @@ -1886,8 +1940,10 @@ async def sample_create_service_rollout(): retry (google.api_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. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.api_core.operation_async.AsyncOperation: @@ -1967,7 +2023,7 @@ async def generate_config_report( old_config: Optional[any_pb2.Any] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> servicemanager.GenerateConfigReportResponse: r"""Generates and returns a report (errors, warnings and changes from existing configurations) associated with @@ -2036,8 +2092,10 @@ async def sample_generate_config_report(): retry (google.api_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. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.cloud.servicemanagement_v1.types.GenerateConfigReportResponse: @@ -2093,7 +2151,7 @@ async def list_operations( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operations_pb2.ListOperationsResponse: r"""Lists operations that match the specified filter in the request. @@ -2104,8 +2162,10 @@ async def list_operations( retry (google.api_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. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.operations_pb2.ListOperationsResponse: Response message for ``ListOperations`` method. @@ -2146,7 +2206,7 @@ async def set_iam_policy( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> policy_pb2.Policy: r"""Sets the IAM access control policy on the specified function. @@ -2159,8 +2219,10 @@ async def set_iam_policy( retry (google.api_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. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.policy_pb2.Policy: Defines an Identity and Access Management (IAM) policy. @@ -2265,7 +2327,7 @@ async def get_iam_policy( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> policy_pb2.Policy: r"""Gets the IAM access control policy for a function. @@ -2279,8 +2341,10 @@ async def get_iam_policy( retry (google.api_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. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.policy_pb2.Policy: Defines an Identity and Access Management (IAM) policy. @@ -2385,7 +2449,7 @@ async def test_iam_permissions( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> iam_policy_pb2.TestIamPermissionsResponse: r"""Tests the specified IAM permissions against the IAM access control policy for a function. @@ -2400,8 +2464,10 @@ async def test_iam_permissions( retry (google.api_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. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.iam_policy_pb2.TestIamPermissionsResponse: Response message for ``TestIamPermissions`` method. diff --git a/packages/google-cloud-service-management/google/cloud/servicemanagement_v1/services/service_manager/client.py b/packages/google-cloud-service-management/google/cloud/servicemanagement_v1/services/service_manager/client.py index 43b423e379fd..e9fd8b453b90 100644 --- a/packages/google-cloud-service-management/google/cloud/servicemanagement_v1/services/service_manager/client.py +++ b/packages/google-cloud-service-management/google/cloud/servicemanagement_v1/services/service_manager/client.py @@ -14,6 +14,7 @@ # limitations under the License. # from collections import OrderedDict +import logging as std_logging import os import re from typing import ( @@ -48,6 +49,15 @@ except AttributeError: # pragma: NO COVER OptionalRetry = Union[retries.Retry, object, None] # type: ignore +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + from google.api import auth_pb2 # type: ignore from google.api import backend_pb2 # type: ignore from google.api import billing_pb2 # type: ignore @@ -589,6 +599,10 @@ def __init__( # Initialize the universe domain validation. self._is_universe_domain_valid = False + if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER + # Setup logging. + client_logging.initialize_logging() + api_key_value = getattr(self._client_options, "api_key", None) if api_key_value and credentials: raise ValueError( @@ -654,6 +668,29 @@ def __init__( api_audience=self._client_options.api_audience, ) + if "async" not in str(self._transport): + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.api.servicemanagement_v1.ServiceManagerClient`.", + extra={ + "serviceName": "google.api.servicemanagement.v1.ServiceManager", + "universeDomain": getattr( + self._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._transport, "_credentials") + else { + "serviceName": "google.api.servicemanagement.v1.ServiceManager", + "credentialsType": None, + }, + ) + def list_services( self, request: Optional[Union[servicemanager.ListServicesRequest, dict]] = None, @@ -662,7 +699,7 @@ def list_services( consumer_id: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> pagers.ListServicesPager: r"""Lists managed services. @@ -720,8 +757,10 @@ def sample_list_services(): retry (google.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. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.cloud.servicemanagement_v1.services.service_manager.pagers.ListServicesPager: @@ -788,7 +827,7 @@ def get_service( service_name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> resources.ManagedService: r"""Gets a managed service. Authentication is required unless the service is public. @@ -833,8 +872,10 @@ def sample_get_service(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.cloud.servicemanagement_v1.types.ManagedService: @@ -895,7 +936,7 @@ def create_service( service: Optional[resources.ManagedService] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operation.Operation: r"""Creates a new managed service. @@ -953,8 +994,10 @@ def sample_create_service(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.api_core.operation.Operation: @@ -1016,7 +1059,7 @@ def delete_service( service_name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operation.Operation: r"""Deletes a managed service. This method will change the service to the ``Soft-Delete`` state for 30 days. Within this period, @@ -1073,8 +1116,10 @@ def sample_delete_service(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.api_core.operation.Operation: @@ -1152,7 +1197,7 @@ def undelete_service( service_name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operation.Operation: r"""Revives a previously deleted managed service. The method restores the service using the configuration at @@ -1208,8 +1253,10 @@ def sample_undelete_service(): retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.api_core.operation.Operation: @@ -1280,7 +1327,7 @@ def list_service_configs( service_name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> pagers.ListServiceConfigsPager: r"""Lists the history of the service configuration for a managed service, from the newest to the oldest. @@ -1328,8 +1375,10 @@ def sample_list_service_configs(): retry (google.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. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.cloud.servicemanagement_v1.services.service_manager.pagers.ListServiceConfigsPager: @@ -1405,7 +1454,7 @@ def get_service_config( view: Optional[servicemanager.GetServiceConfigRequest.ConfigView] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> service_pb2.Service: r"""Gets a service configuration (version) for a managed service. @@ -1470,8 +1519,10 @@ def sample_get_service_config(): retry (google.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. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.api.service_pb2.Service: @@ -1568,7 +1619,7 @@ def create_service_config( service_config: Optional[service_pb2.Service] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> service_pb2.Service: r"""Creates a new service configuration (version) for a managed service. This method only stores the service configuration. To @@ -1629,8 +1680,10 @@ def sample_create_service_config(): retry (google.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. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.api.service_pb2.Service: @@ -1721,7 +1774,7 @@ def submit_config_source( validate_only: Optional[bool] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operation.Operation: r"""Creates a new service configuration (version) for a managed service based on user-supplied configuration source files (for @@ -1799,8 +1852,10 @@ def sample_submit_config_source(): retry (google.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. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.api_core.operation.Operation: @@ -1878,7 +1933,7 @@ def list_service_rollouts( filter: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> pagers.ListServiceRolloutsPager: r"""Lists the history of the service configuration rollouts for a managed service, from the newest to the @@ -1943,8 +1998,10 @@ def sample_list_service_rollouts(): retry (google.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. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.cloud.servicemanagement_v1.services.service_manager.pagers.ListServiceRolloutsPager: @@ -2021,7 +2078,7 @@ def get_service_rollout( rollout_id: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> resources.Rollout: r"""Gets a service configuration [rollout][google.api.servicemanagement.v1.Rollout]. @@ -2076,8 +2133,10 @@ def sample_get_service_rollout(): retry (google.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. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.cloud.servicemanagement_v1.types.Rollout: @@ -2149,7 +2208,7 @@ def create_service_rollout( rollout: Optional[resources.Rollout] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operation.Operation: r"""Creates a new service configuration rollout. Based on rollout, the Google Service Management will roll out the @@ -2222,8 +2281,10 @@ def sample_create_service_rollout(): retry (google.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. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.api_core.operation.Operation: @@ -2300,7 +2361,7 @@ def generate_config_report( old_config: Optional[any_pb2.Any] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> servicemanager.GenerateConfigReportResponse: r"""Generates and returns a report (errors, warnings and changes from existing configurations) associated with @@ -2369,8 +2430,10 @@ def sample_generate_config_report(): retry (google.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. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: google.cloud.servicemanagement_v1.types.GenerateConfigReportResponse: @@ -2436,7 +2499,7 @@ def list_operations( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operations_pb2.ListOperationsResponse: r"""Lists operations that match the specified filter in the request. @@ -2447,8 +2510,10 @@ def list_operations( retry (google.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. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.operations_pb2.ListOperationsResponse: Response message for ``ListOperations`` method. @@ -2489,7 +2554,7 @@ def set_iam_policy( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> policy_pb2.Policy: r"""Sets the IAM access control policy on the specified function. @@ -2502,8 +2567,10 @@ def set_iam_policy( retry (google.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. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.policy_pb2.Policy: Defines an Identity and Access Management (IAM) policy. @@ -2608,7 +2675,7 @@ def get_iam_policy( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> policy_pb2.Policy: r"""Gets the IAM access control policy for a function. @@ -2622,8 +2689,10 @@ def get_iam_policy( retry (google.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. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.policy_pb2.Policy: Defines an Identity and Access Management (IAM) policy. @@ -2728,7 +2797,7 @@ def test_iam_permissions( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> iam_policy_pb2.TestIamPermissionsResponse: r"""Tests the specified IAM permissions against the IAM access control policy for a function. @@ -2743,8 +2812,10 @@ def test_iam_permissions( retry (google.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. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.iam_policy_pb2.TestIamPermissionsResponse: Response message for ``TestIamPermissions`` method. diff --git a/packages/google-cloud-service-management/google/cloud/servicemanagement_v1/services/service_manager/pagers.py b/packages/google-cloud-service-management/google/cloud/servicemanagement_v1/services/service_manager/pagers.py index 10cabfe9ddc7..e73be0df9ad7 100644 --- a/packages/google-cloud-service-management/google/cloud/servicemanagement_v1/services/service_manager/pagers.py +++ b/packages/google-cloud-service-management/google/cloud/servicemanagement_v1/services/service_manager/pagers.py @@ -69,7 +69,7 @@ def __init__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = () + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () ): """Instantiate the pager. @@ -83,8 +83,10 @@ def __init__( retry (google.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. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. """ self._method = method self._request = servicemanager.ListServicesRequest(request) @@ -143,7 +145,7 @@ def __init__( *, retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = () + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () ): """Instantiates the pager. @@ -157,8 +159,10 @@ def __init__( retry (google.api_core.retry.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. """ self._method = method self._request = servicemanager.ListServicesRequest(request) @@ -221,7 +225,7 @@ def __init__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = () + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () ): """Instantiate the pager. @@ -235,8 +239,10 @@ def __init__( retry (google.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. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. """ self._method = method self._request = servicemanager.ListServiceConfigsRequest(request) @@ -295,7 +301,7 @@ def __init__( *, retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = () + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () ): """Instantiates the pager. @@ -309,8 +315,10 @@ def __init__( retry (google.api_core.retry.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. """ self._method = method self._request = servicemanager.ListServiceConfigsRequest(request) @@ -373,7 +381,7 @@ def __init__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = () + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () ): """Instantiate the pager. @@ -387,8 +395,10 @@ def __init__( retry (google.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. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. """ self._method = method self._request = servicemanager.ListServiceRolloutsRequest(request) @@ -447,7 +457,7 @@ def __init__( *, retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = () + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () ): """Instantiates the pager. @@ -461,8 +471,10 @@ def __init__( retry (google.api_core.retry.AsyncRetry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. """ self._method = method self._request = servicemanager.ListServiceRolloutsRequest(request) diff --git a/packages/google-cloud-service-management/google/cloud/servicemanagement_v1/services/service_manager/transports/grpc.py b/packages/google-cloud-service-management/google/cloud/servicemanagement_v1/services/service_manager/transports/grpc.py index dfa7d8015709..5e1080796ceb 100644 --- a/packages/google-cloud-service-management/google/cloud/servicemanagement_v1/services/service_manager/transports/grpc.py +++ b/packages/google-cloud-service-management/google/cloud/servicemanagement_v1/services/service_manager/transports/grpc.py @@ -13,6 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import json +import logging as std_logging +import pickle from typing import Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -24,12 +27,90 @@ 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.json_format import MessageToJson +import google.protobuf.message import grpc # type: ignore +import proto # type: ignore from google.cloud.servicemanagement_v1.types import resources, servicemanager from .base import DEFAULT_CLIENT_INFO, ServiceManagerTransport +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER + def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.api.servicemanagement.v1.ServiceManager", + "rpcName": client_call_details.method, + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + + response = continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = response.result() + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response for {client_call_details.method}.", + extra={ + "serviceName": "google.api.servicemanagement.v1.ServiceManager", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + class ServiceManagerGrpcTransport(ServiceManagerTransport): """gRPC backend transport for ServiceManager. @@ -185,7 +266,12 @@ def __init__( ], ) - # Wrap messages. This must be done after self._grpc_channel exists + self._interceptor = _LoggingClientInterceptor() + self._logged_channel = grpc.intercept_channel( + self._grpc_channel, self._interceptor + ) + + # Wrap messages. This must be done after self._logged_channel exists self._prep_wrapped_messages(client_info) @classmethod @@ -249,7 +335,9 @@ def operations_client(self) -> operations_v1.OperationsClient: """ # 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) + self._operations_client = operations_v1.OperationsClient( + self._logged_channel + ) # Return the client from cache. return self._operations_client @@ -279,7 +367,7 @@ def list_services( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "list_services" not in self._stubs: - self._stubs["list_services"] = self.grpc_channel.unary_unary( + self._stubs["list_services"] = self._logged_channel.unary_unary( "/google.api.servicemanagement.v1.ServiceManager/ListServices", request_serializer=servicemanager.ListServicesRequest.serialize, response_deserializer=servicemanager.ListServicesResponse.deserialize, @@ -306,7 +394,7 @@ def get_service( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "get_service" not in self._stubs: - self._stubs["get_service"] = self.grpc_channel.unary_unary( + self._stubs["get_service"] = self._logged_channel.unary_unary( "/google.api.servicemanagement.v1.ServiceManager/GetService", request_serializer=servicemanager.GetServiceRequest.serialize, response_deserializer=resources.ManagedService.deserialize, @@ -343,7 +431,7 @@ def create_service( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "create_service" not in self._stubs: - self._stubs["create_service"] = self.grpc_channel.unary_unary( + self._stubs["create_service"] = self._logged_channel.unary_unary( "/google.api.servicemanagement.v1.ServiceManager/CreateService", request_serializer=servicemanager.CreateServiceRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, @@ -376,7 +464,7 @@ def delete_service( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "delete_service" not in self._stubs: - self._stubs["delete_service"] = self.grpc_channel.unary_unary( + self._stubs["delete_service"] = self._logged_channel.unary_unary( "/google.api.servicemanagement.v1.ServiceManager/DeleteService", request_serializer=servicemanager.DeleteServiceRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, @@ -408,7 +496,7 @@ def undelete_service( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "undelete_service" not in self._stubs: - self._stubs["undelete_service"] = self.grpc_channel.unary_unary( + self._stubs["undelete_service"] = self._logged_channel.unary_unary( "/google.api.servicemanagement.v1.ServiceManager/UndeleteService", request_serializer=servicemanager.UndeleteServiceRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, @@ -438,7 +526,7 @@ def list_service_configs( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "list_service_configs" not in self._stubs: - self._stubs["list_service_configs"] = self.grpc_channel.unary_unary( + self._stubs["list_service_configs"] = self._logged_channel.unary_unary( "/google.api.servicemanagement.v1.ServiceManager/ListServiceConfigs", request_serializer=servicemanager.ListServiceConfigsRequest.serialize, response_deserializer=servicemanager.ListServiceConfigsResponse.deserialize, @@ -465,7 +553,7 @@ def get_service_config( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "get_service_config" not in self._stubs: - self._stubs["get_service_config"] = self.grpc_channel.unary_unary( + self._stubs["get_service_config"] = self._logged_channel.unary_unary( "/google.api.servicemanagement.v1.ServiceManager/GetServiceConfig", request_serializer=servicemanager.GetServiceConfigRequest.serialize, response_deserializer=service_pb2.Service.FromString, @@ -499,7 +587,7 @@ def create_service_config( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "create_service_config" not in self._stubs: - self._stubs["create_service_config"] = self.grpc_channel.unary_unary( + self._stubs["create_service_config"] = self._logged_channel.unary_unary( "/google.api.servicemanagement.v1.ServiceManager/CreateServiceConfig", request_serializer=servicemanager.CreateServiceConfigRequest.serialize, response_deserializer=service_pb2.Service.FromString, @@ -537,7 +625,7 @@ def submit_config_source( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "submit_config_source" not in self._stubs: - self._stubs["submit_config_source"] = self.grpc_channel.unary_unary( + self._stubs["submit_config_source"] = self._logged_channel.unary_unary( "/google.api.servicemanagement.v1.ServiceManager/SubmitConfigSource", request_serializer=servicemanager.SubmitConfigSourceRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, @@ -568,7 +656,7 @@ def list_service_rollouts( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "list_service_rollouts" not in self._stubs: - self._stubs["list_service_rollouts"] = self.grpc_channel.unary_unary( + self._stubs["list_service_rollouts"] = self._logged_channel.unary_unary( "/google.api.servicemanagement.v1.ServiceManager/ListServiceRollouts", request_serializer=servicemanager.ListServiceRolloutsRequest.serialize, response_deserializer=servicemanager.ListServiceRolloutsResponse.deserialize, @@ -595,7 +683,7 @@ def get_service_rollout( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "get_service_rollout" not in self._stubs: - self._stubs["get_service_rollout"] = self.grpc_channel.unary_unary( + self._stubs["get_service_rollout"] = self._logged_channel.unary_unary( "/google.api.servicemanagement.v1.ServiceManager/GetServiceRollout", request_serializer=servicemanager.GetServiceRolloutRequest.serialize, response_deserializer=resources.Rollout.deserialize, @@ -639,7 +727,7 @@ def create_service_rollout( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "create_service_rollout" not in self._stubs: - self._stubs["create_service_rollout"] = self.grpc_channel.unary_unary( + self._stubs["create_service_rollout"] = self._logged_channel.unary_unary( "/google.api.servicemanagement.v1.ServiceManager/CreateServiceRollout", request_serializer=servicemanager.CreateServiceRolloutRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, @@ -679,7 +767,7 @@ def generate_config_report( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "generate_config_report" not in self._stubs: - self._stubs["generate_config_report"] = self.grpc_channel.unary_unary( + self._stubs["generate_config_report"] = self._logged_channel.unary_unary( "/google.api.servicemanagement.v1.ServiceManager/GenerateConfigReport", request_serializer=servicemanager.GenerateConfigReportRequest.serialize, response_deserializer=servicemanager.GenerateConfigReportResponse.deserialize, @@ -687,7 +775,7 @@ def generate_config_report( return self._stubs["generate_config_report"] def close(self): - self.grpc_channel.close() + self._logged_channel.close() @property def list_operations( @@ -701,7 +789,7 @@ def list_operations( # 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( + self._stubs["list_operations"] = self._logged_channel.unary_unary( "/google.longrunning.Operations/ListOperations", request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, response_deserializer=operations_pb2.ListOperationsResponse.FromString, @@ -726,7 +814,7 @@ def set_iam_policy( # 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( + self._stubs["set_iam_policy"] = self._logged_channel.unary_unary( "/google.iam.v1.IAMPolicy/SetIamPolicy", request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, response_deserializer=policy_pb2.Policy.FromString, @@ -752,7 +840,7 @@ def get_iam_policy( # 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( + self._stubs["get_iam_policy"] = self._logged_channel.unary_unary( "/google.iam.v1.IAMPolicy/GetIamPolicy", request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, response_deserializer=policy_pb2.Policy.FromString, @@ -781,7 +869,7 @@ def test_iam_permissions( # 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( + self._stubs["test_iam_permissions"] = self._logged_channel.unary_unary( "/google.iam.v1.IAMPolicy/TestIamPermissions", request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, diff --git a/packages/google-cloud-service-management/google/cloud/servicemanagement_v1/services/service_manager/transports/grpc_asyncio.py b/packages/google-cloud-service-management/google/cloud/servicemanagement_v1/services/service_manager/transports/grpc_asyncio.py index 938812c9266e..789141a54a3e 100644 --- a/packages/google-cloud-service-management/google/cloud/servicemanagement_v1/services/service_manager/transports/grpc_asyncio.py +++ b/packages/google-cloud-service-management/google/cloud/servicemanagement_v1/services/service_manager/transports/grpc_asyncio.py @@ -14,6 +14,9 @@ # limitations under the License. # import inspect +import json +import logging as std_logging +import pickle from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings @@ -26,14 +29,93 @@ 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.json_format import MessageToJson +import google.protobuf.message import grpc # type: ignore from grpc.experimental import aio # type: ignore +import proto # type: ignore from google.cloud.servicemanagement_v1.types import resources, servicemanager from .base import DEFAULT_CLIENT_INFO, ServiceManagerTransport from .grpc import ServiceManagerGrpcTransport +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientAIOInterceptor( + grpc.aio.UnaryUnaryClientInterceptor +): # pragma: NO COVER + async def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.api.servicemanagement.v1.ServiceManager", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = await continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = await response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = await response + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response to rpc {client_call_details.method}.", + extra={ + "serviceName": "google.api.servicemanagement.v1.ServiceManager", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + class ServiceManagerGrpcAsyncIOTransport(ServiceManagerTransport): """gRPC AsyncIO backend transport for ServiceManager. @@ -232,10 +314,13 @@ def __init__( ], ) - # Wrap messages. This must be done after self._grpc_channel exists + self._interceptor = _LoggingClientAIOInterceptor() + self._grpc_channel._unary_unary_interceptors.append(self._interceptor) + self._logged_channel = self._grpc_channel self._wrap_with_kind = ( "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters ) + # Wrap messages. This must be done after self._logged_channel exists self._prep_wrapped_messages(client_info) @property @@ -258,7 +343,7 @@ def operations_client(self) -> operations_v1.OperationsAsyncClient: # 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 + self._logged_channel ) # Return the client from cache. @@ -290,7 +375,7 @@ def list_services( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "list_services" not in self._stubs: - self._stubs["list_services"] = self.grpc_channel.unary_unary( + self._stubs["list_services"] = self._logged_channel.unary_unary( "/google.api.servicemanagement.v1.ServiceManager/ListServices", request_serializer=servicemanager.ListServicesRequest.serialize, response_deserializer=servicemanager.ListServicesResponse.deserialize, @@ -319,7 +404,7 @@ def get_service( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "get_service" not in self._stubs: - self._stubs["get_service"] = self.grpc_channel.unary_unary( + self._stubs["get_service"] = self._logged_channel.unary_unary( "/google.api.servicemanagement.v1.ServiceManager/GetService", request_serializer=servicemanager.GetServiceRequest.serialize, response_deserializer=resources.ManagedService.deserialize, @@ -358,7 +443,7 @@ def create_service( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "create_service" not in self._stubs: - self._stubs["create_service"] = self.grpc_channel.unary_unary( + self._stubs["create_service"] = self._logged_channel.unary_unary( "/google.api.servicemanagement.v1.ServiceManager/CreateService", request_serializer=servicemanager.CreateServiceRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, @@ -393,7 +478,7 @@ def delete_service( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "delete_service" not in self._stubs: - self._stubs["delete_service"] = self.grpc_channel.unary_unary( + self._stubs["delete_service"] = self._logged_channel.unary_unary( "/google.api.servicemanagement.v1.ServiceManager/DeleteService", request_serializer=servicemanager.DeleteServiceRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, @@ -427,7 +512,7 @@ def undelete_service( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "undelete_service" not in self._stubs: - self._stubs["undelete_service"] = self.grpc_channel.unary_unary( + self._stubs["undelete_service"] = self._logged_channel.unary_unary( "/google.api.servicemanagement.v1.ServiceManager/UndeleteService", request_serializer=servicemanager.UndeleteServiceRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, @@ -457,7 +542,7 @@ def list_service_configs( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "list_service_configs" not in self._stubs: - self._stubs["list_service_configs"] = self.grpc_channel.unary_unary( + self._stubs["list_service_configs"] = self._logged_channel.unary_unary( "/google.api.servicemanagement.v1.ServiceManager/ListServiceConfigs", request_serializer=servicemanager.ListServiceConfigsRequest.serialize, response_deserializer=servicemanager.ListServiceConfigsResponse.deserialize, @@ -486,7 +571,7 @@ def get_service_config( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "get_service_config" not in self._stubs: - self._stubs["get_service_config"] = self.grpc_channel.unary_unary( + self._stubs["get_service_config"] = self._logged_channel.unary_unary( "/google.api.servicemanagement.v1.ServiceManager/GetServiceConfig", request_serializer=servicemanager.GetServiceConfigRequest.serialize, response_deserializer=service_pb2.Service.FromString, @@ -522,7 +607,7 @@ def create_service_config( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "create_service_config" not in self._stubs: - self._stubs["create_service_config"] = self.grpc_channel.unary_unary( + self._stubs["create_service_config"] = self._logged_channel.unary_unary( "/google.api.servicemanagement.v1.ServiceManager/CreateServiceConfig", request_serializer=servicemanager.CreateServiceConfigRequest.serialize, response_deserializer=service_pb2.Service.FromString, @@ -562,7 +647,7 @@ def submit_config_source( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "submit_config_source" not in self._stubs: - self._stubs["submit_config_source"] = self.grpc_channel.unary_unary( + self._stubs["submit_config_source"] = self._logged_channel.unary_unary( "/google.api.servicemanagement.v1.ServiceManager/SubmitConfigSource", request_serializer=servicemanager.SubmitConfigSourceRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, @@ -593,7 +678,7 @@ def list_service_rollouts( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "list_service_rollouts" not in self._stubs: - self._stubs["list_service_rollouts"] = self.grpc_channel.unary_unary( + self._stubs["list_service_rollouts"] = self._logged_channel.unary_unary( "/google.api.servicemanagement.v1.ServiceManager/ListServiceRollouts", request_serializer=servicemanager.ListServiceRolloutsRequest.serialize, response_deserializer=servicemanager.ListServiceRolloutsResponse.deserialize, @@ -622,7 +707,7 @@ def get_service_rollout( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "get_service_rollout" not in self._stubs: - self._stubs["get_service_rollout"] = self.grpc_channel.unary_unary( + self._stubs["get_service_rollout"] = self._logged_channel.unary_unary( "/google.api.servicemanagement.v1.ServiceManager/GetServiceRollout", request_serializer=servicemanager.GetServiceRolloutRequest.serialize, response_deserializer=resources.Rollout.deserialize, @@ -667,7 +752,7 @@ def create_service_rollout( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "create_service_rollout" not in self._stubs: - self._stubs["create_service_rollout"] = self.grpc_channel.unary_unary( + self._stubs["create_service_rollout"] = self._logged_channel.unary_unary( "/google.api.servicemanagement.v1.ServiceManager/CreateServiceRollout", request_serializer=servicemanager.CreateServiceRolloutRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, @@ -707,7 +792,7 @@ def generate_config_report( # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "generate_config_report" not in self._stubs: - self._stubs["generate_config_report"] = self.grpc_channel.unary_unary( + self._stubs["generate_config_report"] = self._logged_channel.unary_unary( "/google.api.servicemanagement.v1.ServiceManager/GenerateConfigReport", request_serializer=servicemanager.GenerateConfigReportRequest.serialize, response_deserializer=servicemanager.GenerateConfigReportResponse.deserialize, @@ -810,7 +895,7 @@ def _wrap_method(self, func, *args, **kwargs): return gapic_v1.method_async.wrap_method(func, *args, **kwargs) def close(self): - return self.grpc_channel.close() + return self._logged_channel.close() @property def kind(self) -> str: @@ -828,7 +913,7 @@ def list_operations( # 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( + self._stubs["list_operations"] = self._logged_channel.unary_unary( "/google.longrunning.Operations/ListOperations", request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, response_deserializer=operations_pb2.ListOperationsResponse.FromString, @@ -853,7 +938,7 @@ def set_iam_policy( # 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( + self._stubs["set_iam_policy"] = self._logged_channel.unary_unary( "/google.iam.v1.IAMPolicy/SetIamPolicy", request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, response_deserializer=policy_pb2.Policy.FromString, @@ -879,7 +964,7 @@ def get_iam_policy( # 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( + self._stubs["get_iam_policy"] = self._logged_channel.unary_unary( "/google.iam.v1.IAMPolicy/GetIamPolicy", request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, response_deserializer=policy_pb2.Policy.FromString, @@ -908,7 +993,7 @@ def test_iam_permissions( # 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( + self._stubs["test_iam_permissions"] = self._logged_channel.unary_unary( "/google.iam.v1.IAMPolicy/TestIamPermissions", request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, diff --git a/packages/google-cloud-service-management/google/cloud/servicemanagement_v1/services/service_manager/transports/rest.py b/packages/google-cloud-service-management/google/cloud/servicemanagement_v1/services/service_manager/transports/rest.py index 12252f7cd1f8..08da19ee9a40 100644 --- a/packages/google-cloud-service-management/google/cloud/servicemanagement_v1/services/service_manager/transports/rest.py +++ b/packages/google-cloud-service-management/google/cloud/servicemanagement_v1/services/service_manager/transports/rest.py @@ -13,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import dataclasses import json # type: ignore +import logging from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union import warnings @@ -41,6 +41,14 @@ except AttributeError: # pragma: NO COVER OptionalRetry = Union[retries.Retry, object, None] # type: ignore +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = logging.getLogger(__name__) DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, @@ -177,8 +185,10 @@ def post_undelete_service(self, response): def pre_create_service( self, request: servicemanager.CreateServiceRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[servicemanager.CreateServiceRequest, Sequence[Tuple[str, str]]]: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + servicemanager.CreateServiceRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for create_service Override in a subclass to manipulate the request or metadata @@ -200,8 +210,11 @@ def post_create_service( def pre_create_service_config( self, request: servicemanager.CreateServiceConfigRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[servicemanager.CreateServiceConfigRequest, Sequence[Tuple[str, str]]]: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + servicemanager.CreateServiceConfigRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for create_service_config Override in a subclass to manipulate the request or metadata @@ -223,8 +236,11 @@ def post_create_service_config( def pre_create_service_rollout( self, request: servicemanager.CreateServiceRolloutRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[servicemanager.CreateServiceRolloutRequest, Sequence[Tuple[str, str]]]: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + servicemanager.CreateServiceRolloutRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for create_service_rollout Override in a subclass to manipulate the request or metadata @@ -246,8 +262,10 @@ def post_create_service_rollout( def pre_delete_service( self, request: servicemanager.DeleteServiceRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[servicemanager.DeleteServiceRequest, Sequence[Tuple[str, str]]]: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + servicemanager.DeleteServiceRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for delete_service Override in a subclass to manipulate the request or metadata @@ -269,8 +287,11 @@ def post_delete_service( def pre_generate_config_report( self, request: servicemanager.GenerateConfigReportRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[servicemanager.GenerateConfigReportRequest, Sequence[Tuple[str, str]]]: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + servicemanager.GenerateConfigReportRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for generate_config_report Override in a subclass to manipulate the request or metadata @@ -292,8 +313,10 @@ def post_generate_config_report( def pre_get_service( self, request: servicemanager.GetServiceRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[servicemanager.GetServiceRequest, Sequence[Tuple[str, str]]]: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + servicemanager.GetServiceRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for get_service Override in a subclass to manipulate the request or metadata @@ -315,8 +338,10 @@ def post_get_service( def pre_get_service_config( self, request: servicemanager.GetServiceConfigRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[servicemanager.GetServiceConfigRequest, Sequence[Tuple[str, str]]]: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + servicemanager.GetServiceConfigRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for get_service_config Override in a subclass to manipulate the request or metadata @@ -338,8 +363,10 @@ def post_get_service_config( def pre_get_service_rollout( self, request: servicemanager.GetServiceRolloutRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[servicemanager.GetServiceRolloutRequest, Sequence[Tuple[str, str]]]: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + servicemanager.GetServiceRolloutRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for get_service_rollout Override in a subclass to manipulate the request or metadata @@ -361,8 +388,11 @@ def post_get_service_rollout( def pre_list_service_configs( self, request: servicemanager.ListServiceConfigsRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[servicemanager.ListServiceConfigsRequest, Sequence[Tuple[str, str]]]: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + servicemanager.ListServiceConfigsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for list_service_configs Override in a subclass to manipulate the request or metadata @@ -384,8 +414,11 @@ def post_list_service_configs( def pre_list_service_rollouts( self, request: servicemanager.ListServiceRolloutsRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[servicemanager.ListServiceRolloutsRequest, Sequence[Tuple[str, str]]]: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + servicemanager.ListServiceRolloutsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for list_service_rollouts Override in a subclass to manipulate the request or metadata @@ -407,8 +440,10 @@ def post_list_service_rollouts( def pre_list_services( self, request: servicemanager.ListServicesRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[servicemanager.ListServicesRequest, Sequence[Tuple[str, str]]]: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + servicemanager.ListServicesRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for list_services Override in a subclass to manipulate the request or metadata @@ -430,8 +465,11 @@ def post_list_services( def pre_submit_config_source( self, request: servicemanager.SubmitConfigSourceRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[servicemanager.SubmitConfigSourceRequest, Sequence[Tuple[str, str]]]: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + servicemanager.SubmitConfigSourceRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for submit_config_source Override in a subclass to manipulate the request or metadata @@ -453,8 +491,10 @@ def post_submit_config_source( def pre_undelete_service( self, request: servicemanager.UndeleteServiceRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[servicemanager.UndeleteServiceRequest, Sequence[Tuple[str, str]]]: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + servicemanager.UndeleteServiceRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for undelete_service Override in a subclass to manipulate the request or metadata @@ -476,8 +516,10 @@ def post_undelete_service( 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]]]: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for get_iam_policy Override in a subclass to manipulate the request or metadata @@ -497,8 +539,10 @@ def post_get_iam_policy(self, response: policy_pb2.Policy) -> policy_pb2.Policy: 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]]]: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for set_iam_policy Override in a subclass to manipulate the request or metadata @@ -518,8 +562,11 @@ def post_set_iam_policy(self, response: policy_pb2.Policy) -> policy_pb2.Policy: 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]]]: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + iam_policy_pb2.TestIamPermissionsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: """Pre-rpc interceptor for test_iam_permissions Override in a subclass to manipulate the request or metadata @@ -541,8 +588,10 @@ def post_test_iam_permissions( def pre_list_operations( self, request: operations_pb2.ListOperationsRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.ListOperationsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: """Pre-rpc interceptor for list_operations Override in a subclass to manipulate the request or metadata @@ -719,7 +768,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operations_pb2.Operation: r"""Call the create service method over HTTP. @@ -730,8 +779,10 @@ def __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. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.operations_pb2.Operation: @@ -744,6 +795,7 @@ def __call__( http_options = ( _BaseServiceManagerRestTransport._BaseCreateService._get_http_options() ) + request, metadata = self._interceptor.pre_create_service(request, metadata) transcoded_request = _BaseServiceManagerRestTransport._BaseCreateService._get_transcoded_request( http_options, request @@ -758,6 +810,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.api.servicemanagement_v1.ServiceManagerClient.CreateService", + extra={ + "serviceName": "google.api.servicemanagement.v1.ServiceManager", + "rpcName": "CreateService", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = ServiceManagerRestTransport._CreateService._get_response( self._host, @@ -777,7 +856,29 @@ def __call__( # Return the response resp = operations_pb2.Operation() json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_service(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.api.servicemanagement_v1.ServiceManagerClient.create_service", + extra={ + "serviceName": "google.api.servicemanagement.v1.ServiceManager", + "rpcName": "CreateService", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp class _CreateServiceConfig( @@ -816,7 +917,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> service_pb2.Service: r"""Call the create service config method over HTTP. @@ -827,8 +928,10 @@ def __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. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.service_pb2.Service: @@ -875,6 +978,7 @@ def __call__( http_options = ( _BaseServiceManagerRestTransport._BaseCreateServiceConfig._get_http_options() ) + request, metadata = self._interceptor.pre_create_service_config( request, metadata ) @@ -891,6 +995,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.api.servicemanagement_v1.ServiceManagerClient.CreateServiceConfig", + extra={ + "serviceName": "google.api.servicemanagement.v1.ServiceManager", + "rpcName": "CreateServiceConfig", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = ServiceManagerRestTransport._CreateServiceConfig._get_response( self._host, @@ -912,7 +1043,29 @@ def __call__( pb_resp = resp json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_service_config(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.api.servicemanagement_v1.ServiceManagerClient.create_service_config", + extra={ + "serviceName": "google.api.servicemanagement.v1.ServiceManager", + "rpcName": "CreateServiceConfig", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp class _CreateServiceRollout( @@ -951,7 +1104,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operations_pb2.Operation: r"""Call the create service rollout method over HTTP. @@ -962,8 +1115,10 @@ def __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. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.operations_pb2.Operation: @@ -976,6 +1131,7 @@ def __call__( http_options = ( _BaseServiceManagerRestTransport._BaseCreateServiceRollout._get_http_options() ) + request, metadata = self._interceptor.pre_create_service_rollout( request, metadata ) @@ -992,6 +1148,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.api.servicemanagement_v1.ServiceManagerClient.CreateServiceRollout", + extra={ + "serviceName": "google.api.servicemanagement.v1.ServiceManager", + "rpcName": "CreateServiceRollout", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = ServiceManagerRestTransport._CreateServiceRollout._get_response( self._host, @@ -1011,7 +1194,29 @@ def __call__( # Return the response resp = operations_pb2.Operation() json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_service_rollout(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.api.servicemanagement_v1.ServiceManagerClient.create_service_rollout", + extra={ + "serviceName": "google.api.servicemanagement.v1.ServiceManager", + "rpcName": "CreateServiceRollout", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp class _DeleteService( @@ -1048,7 +1253,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operations_pb2.Operation: r"""Call the delete service method over HTTP. @@ -1059,8 +1264,10 @@ def __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. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.operations_pb2.Operation: @@ -1073,6 +1280,7 @@ def __call__( http_options = ( _BaseServiceManagerRestTransport._BaseDeleteService._get_http_options() ) + request, metadata = self._interceptor.pre_delete_service(request, metadata) transcoded_request = _BaseServiceManagerRestTransport._BaseDeleteService._get_transcoded_request( http_options, request @@ -1083,6 +1291,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.api.servicemanagement_v1.ServiceManagerClient.DeleteService", + extra={ + "serviceName": "google.api.servicemanagement.v1.ServiceManager", + "rpcName": "DeleteService", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = ServiceManagerRestTransport._DeleteService._get_response( self._host, @@ -1101,7 +1336,29 @@ def __call__( # Return the response resp = operations_pb2.Operation() json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_service(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.api.servicemanagement_v1.ServiceManagerClient.delete_service", + extra={ + "serviceName": "google.api.servicemanagement.v1.ServiceManager", + "rpcName": "DeleteService", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp class _GenerateConfigReport( @@ -1140,7 +1397,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> servicemanager.GenerateConfigReportResponse: r"""Call the generate config report method over HTTP. @@ -1151,8 +1408,10 @@ def __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. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.servicemanager.GenerateConfigReportResponse: @@ -1164,6 +1423,7 @@ def __call__( http_options = ( _BaseServiceManagerRestTransport._BaseGenerateConfigReport._get_http_options() ) + request, metadata = self._interceptor.pre_generate_config_report( request, metadata ) @@ -1180,6 +1440,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.api.servicemanagement_v1.ServiceManagerClient.GenerateConfigReport", + extra={ + "serviceName": "google.api.servicemanagement.v1.ServiceManager", + "rpcName": "GenerateConfigReport", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = ServiceManagerRestTransport._GenerateConfigReport._get_response( self._host, @@ -1201,7 +1488,31 @@ def __call__( pb_resp = servicemanager.GenerateConfigReportResponse.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_generate_config_report(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + servicemanager.GenerateConfigReportResponse.to_json(response) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.api.servicemanagement_v1.ServiceManagerClient.generate_config_report", + extra={ + "serviceName": "google.api.servicemanagement.v1.ServiceManager", + "rpcName": "GenerateConfigReport", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp class _GetService( @@ -1238,7 +1549,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> resources.ManagedService: r"""Call the get service method over HTTP. @@ -1248,8 +1559,10 @@ def __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. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.resources.ManagedService: @@ -1262,6 +1575,7 @@ def __call__( http_options = ( _BaseServiceManagerRestTransport._BaseGetService._get_http_options() ) + request, metadata = self._interceptor.pre_get_service(request, metadata) transcoded_request = _BaseServiceManagerRestTransport._BaseGetService._get_transcoded_request( http_options, request @@ -1274,6 +1588,33 @@ def __call__( ) ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.api.servicemanagement_v1.ServiceManagerClient.GetService", + extra={ + "serviceName": "google.api.servicemanagement.v1.ServiceManager", + "rpcName": "GetService", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = ServiceManagerRestTransport._GetService._get_response( self._host, @@ -1294,7 +1635,29 @@ def __call__( pb_resp = resources.ManagedService.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_service(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = resources.ManagedService.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.api.servicemanagement_v1.ServiceManagerClient.get_service", + extra={ + "serviceName": "google.api.servicemanagement.v1.ServiceManager", + "rpcName": "GetService", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp class _GetServiceConfig( @@ -1331,7 +1694,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> service_pb2.Service: r"""Call the get service config method over HTTP. @@ -1342,8 +1705,10 @@ def __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. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.service_pb2.Service: @@ -1390,6 +1755,7 @@ def __call__( http_options = ( _BaseServiceManagerRestTransport._BaseGetServiceConfig._get_http_options() ) + request, metadata = self._interceptor.pre_get_service_config( request, metadata ) @@ -1402,6 +1768,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.api.servicemanagement_v1.ServiceManagerClient.GetServiceConfig", + extra={ + "serviceName": "google.api.servicemanagement.v1.ServiceManager", + "rpcName": "GetServiceConfig", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = ServiceManagerRestTransport._GetServiceConfig._get_response( self._host, @@ -1422,7 +1815,29 @@ def __call__( pb_resp = resp json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_service_config(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.api.servicemanagement_v1.ServiceManagerClient.get_service_config", + extra={ + "serviceName": "google.api.servicemanagement.v1.ServiceManager", + "rpcName": "GetServiceConfig", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp class _GetServiceRollout( @@ -1459,7 +1874,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> resources.Rollout: r"""Call the get service rollout method over HTTP. @@ -1470,8 +1885,10 @@ def __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. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.resources.Rollout: @@ -1487,6 +1904,7 @@ def __call__( http_options = ( _BaseServiceManagerRestTransport._BaseGetServiceRollout._get_http_options() ) + request, metadata = self._interceptor.pre_get_service_rollout( request, metadata ) @@ -1499,6 +1917,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.api.servicemanagement_v1.ServiceManagerClient.GetServiceRollout", + extra={ + "serviceName": "google.api.servicemanagement.v1.ServiceManager", + "rpcName": "GetServiceRollout", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = ServiceManagerRestTransport._GetServiceRollout._get_response( self._host, @@ -1519,7 +1964,29 @@ def __call__( pb_resp = resources.Rollout.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_service_rollout(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = resources.Rollout.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.api.servicemanagement_v1.ServiceManagerClient.get_service_rollout", + extra={ + "serviceName": "google.api.servicemanagement.v1.ServiceManager", + "rpcName": "GetServiceRollout", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp class _ListServiceConfigs( @@ -1556,7 +2023,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> servicemanager.ListServiceConfigsResponse: r"""Call the list service configs method over HTTP. @@ -1567,8 +2034,10 @@ def __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. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.servicemanager.ListServiceConfigsResponse: @@ -1580,6 +2049,7 @@ def __call__( http_options = ( _BaseServiceManagerRestTransport._BaseListServiceConfigs._get_http_options() ) + request, metadata = self._interceptor.pre_list_service_configs( request, metadata ) @@ -1592,6 +2062,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.api.servicemanagement_v1.ServiceManagerClient.ListServiceConfigs", + extra={ + "serviceName": "google.api.servicemanagement.v1.ServiceManager", + "rpcName": "ListServiceConfigs", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = ServiceManagerRestTransport._ListServiceConfigs._get_response( self._host, @@ -1612,7 +2109,31 @@ def __call__( pb_resp = servicemanager.ListServiceConfigsResponse.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_service_configs(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + servicemanager.ListServiceConfigsResponse.to_json(response) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.api.servicemanagement_v1.ServiceManagerClient.list_service_configs", + extra={ + "serviceName": "google.api.servicemanagement.v1.ServiceManager", + "rpcName": "ListServiceConfigs", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp class _ListServiceRollouts( @@ -1650,7 +2171,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> servicemanager.ListServiceRolloutsResponse: r"""Call the list service rollouts method over HTTP. @@ -1661,8 +2182,10 @@ def __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. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.servicemanager.ListServiceRolloutsResponse: @@ -1674,6 +2197,7 @@ def __call__( http_options = ( _BaseServiceManagerRestTransport._BaseListServiceRollouts._get_http_options() ) + request, metadata = self._interceptor.pre_list_service_rollouts( request, metadata ) @@ -1686,6 +2210,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.api.servicemanagement_v1.ServiceManagerClient.ListServiceRollouts", + extra={ + "serviceName": "google.api.servicemanagement.v1.ServiceManager", + "rpcName": "ListServiceRollouts", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = ServiceManagerRestTransport._ListServiceRollouts._get_response( self._host, @@ -1706,7 +2257,31 @@ def __call__( pb_resp = servicemanager.ListServiceRolloutsResponse.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_service_rollouts(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + servicemanager.ListServiceRolloutsResponse.to_json(response) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.api.servicemanagement_v1.ServiceManagerClient.list_service_rollouts", + extra={ + "serviceName": "google.api.servicemanagement.v1.ServiceManager", + "rpcName": "ListServiceRollouts", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp class _ListServices( @@ -1743,7 +2318,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> servicemanager.ListServicesResponse: r"""Call the list services method over HTTP. @@ -1753,8 +2328,10 @@ def __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. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.servicemanager.ListServicesResponse: @@ -1764,6 +2341,7 @@ def __call__( http_options = ( _BaseServiceManagerRestTransport._BaseListServices._get_http_options() ) + request, metadata = self._interceptor.pre_list_services(request, metadata) transcoded_request = _BaseServiceManagerRestTransport._BaseListServices._get_transcoded_request( http_options, request @@ -1774,6 +2352,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.api.servicemanagement_v1.ServiceManagerClient.ListServices", + extra={ + "serviceName": "google.api.servicemanagement.v1.ServiceManager", + "rpcName": "ListServices", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = ServiceManagerRestTransport._ListServices._get_response( self._host, @@ -1794,7 +2399,31 @@ def __call__( pb_resp = servicemanager.ListServicesResponse.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_services(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = servicemanager.ListServicesResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.api.servicemanagement_v1.ServiceManagerClient.list_services", + extra={ + "serviceName": "google.api.servicemanagement.v1.ServiceManager", + "rpcName": "ListServices", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp class _SubmitConfigSource( @@ -1832,7 +2461,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operations_pb2.Operation: r"""Call the submit config source method over HTTP. @@ -1843,8 +2472,10 @@ def __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. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.operations_pb2.Operation: @@ -1857,6 +2488,7 @@ def __call__( http_options = ( _BaseServiceManagerRestTransport._BaseSubmitConfigSource._get_http_options() ) + request, metadata = self._interceptor.pre_submit_config_source( request, metadata ) @@ -1873,6 +2505,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.api.servicemanagement_v1.ServiceManagerClient.SubmitConfigSource", + extra={ + "serviceName": "google.api.servicemanagement.v1.ServiceManager", + "rpcName": "SubmitConfigSource", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = ServiceManagerRestTransport._SubmitConfigSource._get_response( self._host, @@ -1892,7 +2551,29 @@ def __call__( # Return the response resp = operations_pb2.Operation() json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_submit_config_source(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.api.servicemanagement_v1.ServiceManagerClient.submit_config_source", + extra={ + "serviceName": "google.api.servicemanagement.v1.ServiceManager", + "rpcName": "SubmitConfigSource", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp class _UndeleteService( @@ -1929,7 +2610,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operations_pb2.Operation: r"""Call the undelete service method over HTTP. @@ -1940,8 +2621,10 @@ def __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. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: ~.operations_pb2.Operation: @@ -1954,6 +2637,7 @@ def __call__( http_options = ( _BaseServiceManagerRestTransport._BaseUndeleteService._get_http_options() ) + request, metadata = self._interceptor.pre_undelete_service( request, metadata ) @@ -1966,6 +2650,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.api.servicemanagement_v1.ServiceManagerClient.UndeleteService", + extra={ + "serviceName": "google.api.servicemanagement.v1.ServiceManager", + "rpcName": "UndeleteService", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = ServiceManagerRestTransport._UndeleteService._get_response( self._host, @@ -1984,7 +2695,29 @@ def __call__( # Return the response resp = operations_pb2.Operation() json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_undelete_service(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.api.servicemanagement_v1.ServiceManagerClient.undelete_service", + extra={ + "serviceName": "google.api.servicemanagement.v1.ServiceManager", + "rpcName": "UndeleteService", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) return resp @property @@ -2143,7 +2876,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> policy_pb2.Policy: r"""Call the get iam policy method over HTTP. @@ -2153,8 +2886,10 @@ def __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. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: policy_pb2.Policy: Response from GetIamPolicy method. @@ -2163,6 +2898,7 @@ def __call__( http_options = ( _BaseServiceManagerRestTransport._BaseGetIamPolicy._get_http_options() ) + request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) transcoded_request = _BaseServiceManagerRestTransport._BaseGetIamPolicy._get_transcoded_request( http_options, request @@ -2177,6 +2913,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.api.servicemanagement_v1.ServiceManagerClient.GetIamPolicy", + extra={ + "serviceName": "google.api.servicemanagement.v1.ServiceManager", + "rpcName": "GetIamPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = ServiceManagerRestTransport._GetIamPolicy._get_response( self._host, @@ -2197,6 +2960,27 @@ def __call__( resp = policy_pb2.Policy() resp = json_format.Parse(content, resp) resp = self._interceptor.post_get_iam_policy(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.api.servicemanagement_v1.ServiceManagerAsyncClient.GetIamPolicy", + extra={ + "serviceName": "google.api.servicemanagement.v1.ServiceManager", + "rpcName": "GetIamPolicy", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) return resp @property @@ -2238,7 +3022,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> policy_pb2.Policy: r"""Call the set iam policy method over HTTP. @@ -2248,8 +3032,10 @@ def __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. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: policy_pb2.Policy: Response from SetIamPolicy method. @@ -2258,6 +3044,7 @@ def __call__( http_options = ( _BaseServiceManagerRestTransport._BaseSetIamPolicy._get_http_options() ) + request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) transcoded_request = _BaseServiceManagerRestTransport._BaseSetIamPolicy._get_transcoded_request( http_options, request @@ -2272,6 +3059,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.api.servicemanagement_v1.ServiceManagerClient.SetIamPolicy", + extra={ + "serviceName": "google.api.servicemanagement.v1.ServiceManager", + "rpcName": "SetIamPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = ServiceManagerRestTransport._SetIamPolicy._get_response( self._host, @@ -2292,6 +3106,27 @@ def __call__( resp = policy_pb2.Policy() resp = json_format.Parse(content, resp) resp = self._interceptor.post_set_iam_policy(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.api.servicemanagement_v1.ServiceManagerAsyncClient.SetIamPolicy", + extra={ + "serviceName": "google.api.servicemanagement.v1.ServiceManager", + "rpcName": "SetIamPolicy", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) return resp @property @@ -2333,7 +3168,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> iam_policy_pb2.TestIamPermissionsResponse: r"""Call the test iam permissions method over HTTP. @@ -2343,8 +3178,10 @@ def __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. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: iam_policy_pb2.TestIamPermissionsResponse: Response from TestIamPermissions method. @@ -2353,6 +3190,7 @@ def __call__( http_options = ( _BaseServiceManagerRestTransport._BaseTestIamPermissions._get_http_options() ) + request, metadata = self._interceptor.pre_test_iam_permissions( request, metadata ) @@ -2369,6 +3207,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.api.servicemanagement_v1.ServiceManagerClient.TestIamPermissions", + extra={ + "serviceName": "google.api.servicemanagement.v1.ServiceManager", + "rpcName": "TestIamPermissions", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = ServiceManagerRestTransport._TestIamPermissions._get_response( self._host, @@ -2389,6 +3254,27 @@ def __call__( resp = iam_policy_pb2.TestIamPermissionsResponse() resp = json_format.Parse(content, resp) resp = self._interceptor.post_test_iam_permissions(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.api.servicemanagement_v1.ServiceManagerAsyncClient.TestIamPermissions", + extra={ + "serviceName": "google.api.servicemanagement.v1.ServiceManager", + "rpcName": "TestIamPermissions", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) return resp @property @@ -2429,7 +3315,7 @@ def __call__( *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operations_pb2.ListOperationsResponse: r"""Call the list operations method over HTTP. @@ -2439,8 +3325,10 @@ def __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. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. Returns: operations_pb2.ListOperationsResponse: Response from ListOperations method. @@ -2449,6 +3337,7 @@ def __call__( http_options = ( _BaseServiceManagerRestTransport._BaseListOperations._get_http_options() ) + request, metadata = self._interceptor.pre_list_operations(request, metadata) transcoded_request = _BaseServiceManagerRestTransport._BaseListOperations._get_transcoded_request( http_options, request @@ -2459,6 +3348,33 @@ def __call__( transcoded_request ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.api.servicemanagement_v1.ServiceManagerClient.ListOperations", + extra={ + "serviceName": "google.api.servicemanagement.v1.ServiceManager", + "rpcName": "ListOperations", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + # Send the request response = ServiceManagerRestTransport._ListOperations._get_response( self._host, @@ -2478,6 +3394,27 @@ def __call__( resp = operations_pb2.ListOperationsResponse() resp = json_format.Parse(content, resp) resp = self._interceptor.post_list_operations(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.api.servicemanagement_v1.ServiceManagerAsyncClient.ListOperations", + extra={ + "serviceName": "google.api.servicemanagement.v1.ServiceManager", + "rpcName": "ListOperations", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) return resp @property diff --git a/packages/google-cloud-service-management/samples/generated_samples/snippet_metadata_google.api.servicemanagement.v1.json b/packages/google-cloud-service-management/samples/generated_samples/snippet_metadata_google.api.servicemanagement.v1.json index 8b514f320127..fb37827cecec 100644 --- a/packages/google-cloud-service-management/samples/generated_samples/snippet_metadata_google.api.servicemanagement.v1.json +++ b/packages/google-cloud-service-management/samples/generated_samples/snippet_metadata_google.api.servicemanagement.v1.json @@ -51,7 +51,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.api.service_pb2.Service", @@ -135,7 +135,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.api.service_pb2.Service", @@ -220,7 +220,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.api_core.operation_async.AsyncOperation", @@ -304,7 +304,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.api_core.operation.Operation", @@ -385,7 +385,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.api_core.operation_async.AsyncOperation", @@ -465,7 +465,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.api_core.operation.Operation", @@ -546,7 +546,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.api_core.operation_async.AsyncOperation", @@ -626,7 +626,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.api_core.operation.Operation", @@ -711,7 +711,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.cloud.servicemanagement_v1.types.GenerateConfigReportResponse", @@ -795,7 +795,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.cloud.servicemanagement_v1.types.GenerateConfigReportResponse", @@ -884,7 +884,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.api.service_pb2.Service", @@ -972,7 +972,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.api.service_pb2.Service", @@ -1057,7 +1057,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.cloud.servicemanagement_v1.types.Rollout", @@ -1141,7 +1141,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.cloud.servicemanagement_v1.types.Rollout", @@ -1222,7 +1222,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.cloud.servicemanagement_v1.types.ManagedService", @@ -1302,7 +1302,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.cloud.servicemanagement_v1.types.ManagedService", @@ -1383,7 +1383,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.cloud.servicemanagement_v1.services.service_manager.pagers.ListServiceConfigsAsyncPager", @@ -1463,7 +1463,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.cloud.servicemanagement_v1.services.service_manager.pagers.ListServiceConfigsPager", @@ -1548,7 +1548,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.cloud.servicemanagement_v1.services.service_manager.pagers.ListServiceRolloutsAsyncPager", @@ -1632,7 +1632,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.cloud.servicemanagement_v1.services.service_manager.pagers.ListServiceRolloutsPager", @@ -1717,7 +1717,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.cloud.servicemanagement_v1.services.service_manager.pagers.ListServicesAsyncPager", @@ -1801,7 +1801,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.cloud.servicemanagement_v1.services.service_manager.pagers.ListServicesPager", @@ -1890,7 +1890,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.api_core.operation_async.AsyncOperation", @@ -1978,7 +1978,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.api_core.operation.Operation", @@ -2059,7 +2059,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.api_core.operation_async.AsyncOperation", @@ -2139,7 +2139,7 @@ }, { "name": "metadata", - "type": "Sequence[Tuple[str, str]" + "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], "resultType": "google.api_core.operation.Operation", diff --git a/packages/google-cloud-service-management/tests/unit/gapic/servicemanagement_v1/test_service_manager.py b/packages/google-cloud-service-management/tests/unit/gapic/servicemanagement_v1/test_service_manager.py index 93a54d58d7e6..f453ccc8db3f 100644 --- a/packages/google-cloud-service-management/tests/unit/gapic/servicemanagement_v1/test_service_manager.py +++ b/packages/google-cloud-service-management/tests/unit/gapic/servicemanagement_v1/test_service_manager.py @@ -6115,6 +6115,7 @@ def test_list_services_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.list_services(**mock_args) @@ -6308,6 +6309,7 @@ def test_get_service_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.get_service(request) @@ -6353,6 +6355,7 @@ def test_get_service_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.get_service(**mock_args) @@ -6479,6 +6482,7 @@ def test_create_service_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.create_service(request) @@ -6522,6 +6526,7 @@ def test_create_service_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.create_service(**mock_args) @@ -6652,6 +6657,7 @@ def test_delete_service_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.delete_service(request) @@ -6695,6 +6701,7 @@ def test_delete_service_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.delete_service(**mock_args) @@ -6827,6 +6834,7 @@ def test_undelete_service_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.undelete_service(request) @@ -6870,6 +6878,7 @@ def test_undelete_service_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.undelete_service(**mock_args) @@ -7010,6 +7019,7 @@ def test_list_service_configs_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.list_service_configs(request) @@ -7063,6 +7073,7 @@ def test_list_service_configs_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.list_service_configs(**mock_args) @@ -7263,6 +7274,7 @@ def test_get_service_config_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.get_service_config(request) @@ -7316,6 +7328,7 @@ def test_get_service_config_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.get_service_config(**mock_args) @@ -7453,6 +7466,7 @@ def test_create_service_config_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.create_service_config(request) @@ -7505,6 +7519,7 @@ def test_create_service_config_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.create_service_config(**mock_args) @@ -7641,6 +7656,7 @@ def test_submit_config_source_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.submit_config_source(request) @@ -7694,6 +7710,7 @@ def test_submit_config_source_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.submit_config_source(**mock_args) @@ -7846,6 +7863,7 @@ def test_list_service_rollouts_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.list_service_rollouts(request) @@ -7912,6 +7930,7 @@ def test_list_service_rollouts_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.list_service_rollouts(**mock_args) @@ -8113,6 +8132,7 @@ def test_get_service_rollout_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.get_service_rollout(request) @@ -8167,6 +8187,7 @@ def test_get_service_rollout_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.get_service_rollout(**mock_args) @@ -8306,6 +8327,7 @@ def test_create_service_rollout_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.create_service_rollout(request) @@ -8358,6 +8380,7 @@ def test_create_service_rollout_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.create_service_rollout(**mock_args) @@ -8489,6 +8512,7 @@ def test_generate_config_report_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.generate_config_report(request) @@ -8539,6 +8563,7 @@ def test_generate_config_report_rest_flattened(): json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.generate_config_report(**mock_args) @@ -9376,6 +9401,7 @@ def test_list_services_rest_bad_request( response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.list_services(request) @@ -9411,6 +9437,7 @@ def test_list_services_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.list_services(request) # Establish that the response is the type that we expect. @@ -9451,6 +9478,7 @@ def test_list_services_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} return_value = servicemanager.ListServicesResponse.to_json( servicemanager.ListServicesResponse() ) @@ -9495,6 +9523,7 @@ def test_get_service_rest_bad_request(request_type=servicemanager.GetServiceRequ response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.get_service(request) @@ -9531,6 +9560,7 @@ def test_get_service_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.get_service(request) # Establish that the response is the type that we expect. @@ -9572,6 +9602,7 @@ def test_get_service_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} return_value = resources.ManagedService.to_json(resources.ManagedService()) req.return_value.content = return_value @@ -9616,6 +9647,7 @@ def test_create_service_rest_bad_request( response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.create_service(request) @@ -9717,6 +9749,7 @@ def get_message_fields(field): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.create_service(request) # Establish that the response is the type that we expect. @@ -9758,6 +9791,7 @@ def test_create_service_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} return_value = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.content = return_value @@ -9802,6 +9836,7 @@ def test_delete_service_rest_bad_request( response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.delete_service(request) @@ -9832,6 +9867,7 @@ def test_delete_service_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.delete_service(request) # Establish that the response is the type that we expect. @@ -9873,6 +9909,7 @@ def test_delete_service_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} return_value = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.content = return_value @@ -9917,6 +9954,7 @@ def test_undelete_service_rest_bad_request( response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.undelete_service(request) @@ -9947,6 +9985,7 @@ def test_undelete_service_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.undelete_service(request) # Establish that the response is the type that we expect. @@ -9988,6 +10027,7 @@ def test_undelete_service_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} return_value = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.content = return_value @@ -10032,6 +10072,7 @@ def test_list_service_configs_rest_bad_request( response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.list_service_configs(request) @@ -10067,6 +10108,7 @@ def test_list_service_configs_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.list_service_configs(request) # Establish that the response is the type that we expect. @@ -10107,6 +10149,7 @@ def test_list_service_configs_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} return_value = servicemanager.ListServiceConfigsResponse.to_json( servicemanager.ListServiceConfigsResponse() ) @@ -10153,6 +10196,7 @@ def test_get_service_config_rest_bad_request( response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.get_service_config(request) @@ -10188,6 +10232,7 @@ def test_get_service_config_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.get_service_config(request) # Establish that the response is the type that we expect. @@ -10231,6 +10276,7 @@ def test_get_service_config_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} return_value = json_format.MessageToJson(service_pb2.Service()) req.return_value.content = return_value @@ -10275,6 +10321,7 @@ def test_create_service_config_rest_bad_request( response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.create_service_config(request) @@ -10760,6 +10807,7 @@ def get_message_fields(field): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.create_service_config(request) # Establish that the response is the type that we expect. @@ -10803,6 +10851,7 @@ def test_create_service_config_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} return_value = json_format.MessageToJson(service_pb2.Service()) req.return_value.content = return_value @@ -10847,6 +10896,7 @@ def test_submit_config_source_rest_bad_request( response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.submit_config_source(request) @@ -10877,6 +10927,7 @@ def test_submit_config_source_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.submit_config_source(request) # Establish that the response is the type that we expect. @@ -10918,6 +10969,7 @@ def test_submit_config_source_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} return_value = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.content = return_value @@ -10962,6 +11014,7 @@ def test_list_service_rollouts_rest_bad_request( response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.list_service_rollouts(request) @@ -10997,6 +11050,7 @@ def test_list_service_rollouts_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.list_service_rollouts(request) # Establish that the response is the type that we expect. @@ -11037,6 +11091,7 @@ def test_list_service_rollouts_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} return_value = servicemanager.ListServiceRolloutsResponse.to_json( servicemanager.ListServiceRolloutsResponse() ) @@ -11083,6 +11138,7 @@ def test_get_service_rollout_rest_bad_request( response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.get_service_rollout(request) @@ -11121,6 +11177,7 @@ def test_get_service_rollout_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.get_service_rollout(request) # Establish that the response is the type that we expect. @@ -11164,6 +11221,7 @@ def test_get_service_rollout_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} return_value = resources.Rollout.to_json(resources.Rollout()) req.return_value.content = return_value @@ -11208,6 +11266,7 @@ def test_create_service_rollout_rest_bad_request( response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.create_service_rollout(request) @@ -11314,6 +11373,7 @@ def get_message_fields(field): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.create_service_rollout(request) # Establish that the response is the type that we expect. @@ -11355,6 +11415,7 @@ def test_create_service_rollout_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} return_value = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.content = return_value @@ -11399,6 +11460,7 @@ def test_generate_config_report_rest_bad_request( response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.generate_config_report(request) @@ -11435,6 +11497,7 @@ def test_generate_config_report_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.generate_config_report(request) # Establish that the response is the type that we expect. @@ -11476,6 +11539,7 @@ def test_generate_config_report_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} return_value = servicemanager.GenerateConfigReportResponse.to_json( servicemanager.GenerateConfigReportResponse() ) @@ -11522,6 +11586,7 @@ def test_get_iam_policy_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.get_iam_policy(request) @@ -11552,6 +11617,7 @@ def test_get_iam_policy_rest(request_type): response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.get_iam_policy(request) @@ -11580,6 +11646,7 @@ def test_set_iam_policy_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.set_iam_policy(request) @@ -11610,6 +11677,7 @@ def test_set_iam_policy_rest(request_type): response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.set_iam_policy(request) @@ -11638,6 +11706,7 @@ def test_test_iam_permissions_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.test_iam_permissions(request) @@ -11668,6 +11737,7 @@ def test_test_iam_permissions_rest(request_type): response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.test_iam_permissions(request) @@ -11696,6 +11766,7 @@ def test_list_operations_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} client.list_operations(request) @@ -11726,6 +11797,7 @@ def test_list_operations_rest(request_type): response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} response = client.list_operations(request)