diff --git a/owl-bot-staging/google-cloud-edgecontainer/v1/.coveragerc b/owl-bot-staging/google-cloud-edgecontainer/v1/.coveragerc deleted file mode 100644 index 395fe7b7c2b7..000000000000 --- a/owl-bot-staging/google-cloud-edgecontainer/v1/.coveragerc +++ /dev/null @@ -1,13 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/cloud/edgecontainer/__init__.py - google/cloud/edgecontainer/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-edgecontainer/v1/.flake8 b/owl-bot-staging/google-cloud-edgecontainer/v1/.flake8 deleted file mode 100644 index 29227d4cf419..000000000000 --- a/owl-bot-staging/google-cloud-edgecontainer/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-edgecontainer/v1/MANIFEST.in b/owl-bot-staging/google-cloud-edgecontainer/v1/MANIFEST.in deleted file mode 100644 index 3b796159246b..000000000000 --- a/owl-bot-staging/google-cloud-edgecontainer/v1/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/cloud/edgecontainer *.py -recursive-include google/cloud/edgecontainer_v1 *.py diff --git a/owl-bot-staging/google-cloud-edgecontainer/v1/README.rst b/owl-bot-staging/google-cloud-edgecontainer/v1/README.rst deleted file mode 100644 index 75cfc4964db7..000000000000 --- a/owl-bot-staging/google-cloud-edgecontainer/v1/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Cloud Edgecontainer 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 Edgecontainer 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-edgecontainer/v1/docs/_static/custom.css b/owl-bot-staging/google-cloud-edgecontainer/v1/docs/_static/custom.css deleted file mode 100644 index 06423be0b592..000000000000 --- a/owl-bot-staging/google-cloud-edgecontainer/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-edgecontainer/v1/docs/conf.py b/owl-bot-staging/google-cloud-edgecontainer/v1/docs/conf.py deleted file mode 100644 index ff1115fdffc4..000000000000 --- a/owl-bot-staging/google-cloud-edgecontainer/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-edgecontainer 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-edgecontainer" -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-edgecontainer-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-edgecontainer.tex", - u"google-cloud-edgecontainer 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-edgecontainer", - u"Google Cloud Edgecontainer 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-edgecontainer", - u"google-cloud-edgecontainer Documentation", - author, - "google-cloud-edgecontainer", - "GAPIC library for Google Cloud Edgecontainer 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-edgecontainer/v1/docs/edgecontainer_v1/edge_container.rst b/owl-bot-staging/google-cloud-edgecontainer/v1/docs/edgecontainer_v1/edge_container.rst deleted file mode 100644 index 2c35054cf6cf..000000000000 --- a/owl-bot-staging/google-cloud-edgecontainer/v1/docs/edgecontainer_v1/edge_container.rst +++ /dev/null @@ -1,10 +0,0 @@ -EdgeContainer -------------------------------- - -.. automodule:: google.cloud.edgecontainer_v1.services.edge_container - :members: - :inherited-members: - -.. automodule:: google.cloud.edgecontainer_v1.services.edge_container.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/google-cloud-edgecontainer/v1/docs/edgecontainer_v1/services_.rst b/owl-bot-staging/google-cloud-edgecontainer/v1/docs/edgecontainer_v1/services_.rst deleted file mode 100644 index 0eebab7831d2..000000000000 --- a/owl-bot-staging/google-cloud-edgecontainer/v1/docs/edgecontainer_v1/services_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Services for Google Cloud Edgecontainer v1 API -============================================== -.. toctree:: - :maxdepth: 2 - - edge_container diff --git a/owl-bot-staging/google-cloud-edgecontainer/v1/docs/edgecontainer_v1/types_.rst b/owl-bot-staging/google-cloud-edgecontainer/v1/docs/edgecontainer_v1/types_.rst deleted file mode 100644 index fa5eaae13e4c..000000000000 --- a/owl-bot-staging/google-cloud-edgecontainer/v1/docs/edgecontainer_v1/types_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Types for Google Cloud Edgecontainer v1 API -=========================================== - -.. automodule:: google.cloud.edgecontainer_v1.types - :members: - :show-inheritance: diff --git a/owl-bot-staging/google-cloud-edgecontainer/v1/docs/index.rst b/owl-bot-staging/google-cloud-edgecontainer/v1/docs/index.rst deleted file mode 100644 index bdbb7c09ed11..000000000000 --- a/owl-bot-staging/google-cloud-edgecontainer/v1/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - edgecontainer_v1/services_ - edgecontainer_v1/types_ diff --git a/owl-bot-staging/google-cloud-edgecontainer/v1/google/cloud/edgecontainer/__init__.py b/owl-bot-staging/google-cloud-edgecontainer/v1/google/cloud/edgecontainer/__init__.py deleted file mode 100644 index 0f62f0362b80..000000000000 --- a/owl-bot-staging/google-cloud-edgecontainer/v1/google/cloud/edgecontainer/__init__.py +++ /dev/null @@ -1,119 +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.edgecontainer import gapic_version as package_version - -__version__ = package_version.__version__ - - -from google.cloud.edgecontainer_v1.services.edge_container.client import EdgeContainerClient -from google.cloud.edgecontainer_v1.services.edge_container.async_client import EdgeContainerAsyncClient - -from google.cloud.edgecontainer_v1.types.resources import Authorization -from google.cloud.edgecontainer_v1.types.resources import ChannelConfig -from google.cloud.edgecontainer_v1.types.resources import Cluster -from google.cloud.edgecontainer_v1.types.resources import ClusterNetworking -from google.cloud.edgecontainer_v1.types.resources import ClusterUser -from google.cloud.edgecontainer_v1.types.resources import Fleet -from google.cloud.edgecontainer_v1.types.resources import LocationMetadata -from google.cloud.edgecontainer_v1.types.resources import Machine -from google.cloud.edgecontainer_v1.types.resources import MaintenancePolicy -from google.cloud.edgecontainer_v1.types.resources import MaintenanceWindow -from google.cloud.edgecontainer_v1.types.resources import NodePool -from google.cloud.edgecontainer_v1.types.resources import Quota -from google.cloud.edgecontainer_v1.types.resources import RecurringTimeWindow -from google.cloud.edgecontainer_v1.types.resources import ServerConfig -from google.cloud.edgecontainer_v1.types.resources import TimeWindow -from google.cloud.edgecontainer_v1.types.resources import Version -from google.cloud.edgecontainer_v1.types.resources import VpnConnection -from google.cloud.edgecontainer_v1.types.resources import ZoneMetadata -from google.cloud.edgecontainer_v1.types.resources import KmsKeyState -from google.cloud.edgecontainer_v1.types.service import CreateClusterRequest -from google.cloud.edgecontainer_v1.types.service import CreateNodePoolRequest -from google.cloud.edgecontainer_v1.types.service import CreateVpnConnectionRequest -from google.cloud.edgecontainer_v1.types.service import DeleteClusterRequest -from google.cloud.edgecontainer_v1.types.service import DeleteNodePoolRequest -from google.cloud.edgecontainer_v1.types.service import DeleteVpnConnectionRequest -from google.cloud.edgecontainer_v1.types.service import GenerateAccessTokenRequest -from google.cloud.edgecontainer_v1.types.service import GenerateAccessTokenResponse -from google.cloud.edgecontainer_v1.types.service import GenerateOfflineCredentialRequest -from google.cloud.edgecontainer_v1.types.service import GenerateOfflineCredentialResponse -from google.cloud.edgecontainer_v1.types.service import GetClusterRequest -from google.cloud.edgecontainer_v1.types.service import GetMachineRequest -from google.cloud.edgecontainer_v1.types.service import GetNodePoolRequest -from google.cloud.edgecontainer_v1.types.service import GetServerConfigRequest -from google.cloud.edgecontainer_v1.types.service import GetVpnConnectionRequest -from google.cloud.edgecontainer_v1.types.service import ListClustersRequest -from google.cloud.edgecontainer_v1.types.service import ListClustersResponse -from google.cloud.edgecontainer_v1.types.service import ListMachinesRequest -from google.cloud.edgecontainer_v1.types.service import ListMachinesResponse -from google.cloud.edgecontainer_v1.types.service import ListNodePoolsRequest -from google.cloud.edgecontainer_v1.types.service import ListNodePoolsResponse -from google.cloud.edgecontainer_v1.types.service import ListVpnConnectionsRequest -from google.cloud.edgecontainer_v1.types.service import ListVpnConnectionsResponse -from google.cloud.edgecontainer_v1.types.service import OperationMetadata -from google.cloud.edgecontainer_v1.types.service import UpdateClusterRequest -from google.cloud.edgecontainer_v1.types.service import UpdateNodePoolRequest -from google.cloud.edgecontainer_v1.types.service import UpgradeClusterRequest - -__all__ = ('EdgeContainerClient', - 'EdgeContainerAsyncClient', - 'Authorization', - 'ChannelConfig', - 'Cluster', - 'ClusterNetworking', - 'ClusterUser', - 'Fleet', - 'LocationMetadata', - 'Machine', - 'MaintenancePolicy', - 'MaintenanceWindow', - 'NodePool', - 'Quota', - 'RecurringTimeWindow', - 'ServerConfig', - 'TimeWindow', - 'Version', - 'VpnConnection', - 'ZoneMetadata', - 'KmsKeyState', - 'CreateClusterRequest', - 'CreateNodePoolRequest', - 'CreateVpnConnectionRequest', - 'DeleteClusterRequest', - 'DeleteNodePoolRequest', - 'DeleteVpnConnectionRequest', - 'GenerateAccessTokenRequest', - 'GenerateAccessTokenResponse', - 'GenerateOfflineCredentialRequest', - 'GenerateOfflineCredentialResponse', - 'GetClusterRequest', - 'GetMachineRequest', - 'GetNodePoolRequest', - 'GetServerConfigRequest', - 'GetVpnConnectionRequest', - 'ListClustersRequest', - 'ListClustersResponse', - 'ListMachinesRequest', - 'ListMachinesResponse', - 'ListNodePoolsRequest', - 'ListNodePoolsResponse', - 'ListVpnConnectionsRequest', - 'ListVpnConnectionsResponse', - 'OperationMetadata', - 'UpdateClusterRequest', - 'UpdateNodePoolRequest', - 'UpgradeClusterRequest', -) diff --git a/owl-bot-staging/google-cloud-edgecontainer/v1/google/cloud/edgecontainer/gapic_version.py b/owl-bot-staging/google-cloud-edgecontainer/v1/google/cloud/edgecontainer/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-cloud-edgecontainer/v1/google/cloud/edgecontainer/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-edgecontainer/v1/google/cloud/edgecontainer/py.typed b/owl-bot-staging/google-cloud-edgecontainer/v1/google/cloud/edgecontainer/py.typed deleted file mode 100644 index b447eeb1b655..000000000000 --- a/owl-bot-staging/google-cloud-edgecontainer/v1/google/cloud/edgecontainer/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-edgecontainer package uses inline types. diff --git a/owl-bot-staging/google-cloud-edgecontainer/v1/google/cloud/edgecontainer_v1/__init__.py b/owl-bot-staging/google-cloud-edgecontainer/v1/google/cloud/edgecontainer_v1/__init__.py deleted file mode 100644 index fffc81cc0f6b..000000000000 --- a/owl-bot-staging/google-cloud-edgecontainer/v1/google/cloud/edgecontainer_v1/__init__.py +++ /dev/null @@ -1,120 +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.edgecontainer_v1 import gapic_version as package_version - -__version__ = package_version.__version__ - - -from .services.edge_container import EdgeContainerClient -from .services.edge_container import EdgeContainerAsyncClient - -from .types.resources import Authorization -from .types.resources import ChannelConfig -from .types.resources import Cluster -from .types.resources import ClusterNetworking -from .types.resources import ClusterUser -from .types.resources import Fleet -from .types.resources import LocationMetadata -from .types.resources import Machine -from .types.resources import MaintenancePolicy -from .types.resources import MaintenanceWindow -from .types.resources import NodePool -from .types.resources import Quota -from .types.resources import RecurringTimeWindow -from .types.resources import ServerConfig -from .types.resources import TimeWindow -from .types.resources import Version -from .types.resources import VpnConnection -from .types.resources import ZoneMetadata -from .types.resources import KmsKeyState -from .types.service import CreateClusterRequest -from .types.service import CreateNodePoolRequest -from .types.service import CreateVpnConnectionRequest -from .types.service import DeleteClusterRequest -from .types.service import DeleteNodePoolRequest -from .types.service import DeleteVpnConnectionRequest -from .types.service import GenerateAccessTokenRequest -from .types.service import GenerateAccessTokenResponse -from .types.service import GenerateOfflineCredentialRequest -from .types.service import GenerateOfflineCredentialResponse -from .types.service import GetClusterRequest -from .types.service import GetMachineRequest -from .types.service import GetNodePoolRequest -from .types.service import GetServerConfigRequest -from .types.service import GetVpnConnectionRequest -from .types.service import ListClustersRequest -from .types.service import ListClustersResponse -from .types.service import ListMachinesRequest -from .types.service import ListMachinesResponse -from .types.service import ListNodePoolsRequest -from .types.service import ListNodePoolsResponse -from .types.service import ListVpnConnectionsRequest -from .types.service import ListVpnConnectionsResponse -from .types.service import OperationMetadata -from .types.service import UpdateClusterRequest -from .types.service import UpdateNodePoolRequest -from .types.service import UpgradeClusterRequest - -__all__ = ( - 'EdgeContainerAsyncClient', -'Authorization', -'ChannelConfig', -'Cluster', -'ClusterNetworking', -'ClusterUser', -'CreateClusterRequest', -'CreateNodePoolRequest', -'CreateVpnConnectionRequest', -'DeleteClusterRequest', -'DeleteNodePoolRequest', -'DeleteVpnConnectionRequest', -'EdgeContainerClient', -'Fleet', -'GenerateAccessTokenRequest', -'GenerateAccessTokenResponse', -'GenerateOfflineCredentialRequest', -'GenerateOfflineCredentialResponse', -'GetClusterRequest', -'GetMachineRequest', -'GetNodePoolRequest', -'GetServerConfigRequest', -'GetVpnConnectionRequest', -'KmsKeyState', -'ListClustersRequest', -'ListClustersResponse', -'ListMachinesRequest', -'ListMachinesResponse', -'ListNodePoolsRequest', -'ListNodePoolsResponse', -'ListVpnConnectionsRequest', -'ListVpnConnectionsResponse', -'LocationMetadata', -'Machine', -'MaintenancePolicy', -'MaintenanceWindow', -'NodePool', -'OperationMetadata', -'Quota', -'RecurringTimeWindow', -'ServerConfig', -'TimeWindow', -'UpdateClusterRequest', -'UpdateNodePoolRequest', -'UpgradeClusterRequest', -'Version', -'VpnConnection', -'ZoneMetadata', -) diff --git a/owl-bot-staging/google-cloud-edgecontainer/v1/google/cloud/edgecontainer_v1/gapic_metadata.json b/owl-bot-staging/google-cloud-edgecontainer/v1/google/cloud/edgecontainer_v1/gapic_metadata.json deleted file mode 100644 index fd220d721d7d..000000000000 --- a/owl-bot-staging/google-cloud-edgecontainer/v1/google/cloud/edgecontainer_v1/gapic_metadata.json +++ /dev/null @@ -1,328 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.cloud.edgecontainer_v1", - "protoPackage": "google.cloud.edgecontainer.v1", - "schema": "1.0", - "services": { - "EdgeContainer": { - "clients": { - "grpc": { - "libraryClient": "EdgeContainerClient", - "rpcs": { - "CreateCluster": { - "methods": [ - "create_cluster" - ] - }, - "CreateNodePool": { - "methods": [ - "create_node_pool" - ] - }, - "CreateVpnConnection": { - "methods": [ - "create_vpn_connection" - ] - }, - "DeleteCluster": { - "methods": [ - "delete_cluster" - ] - }, - "DeleteNodePool": { - "methods": [ - "delete_node_pool" - ] - }, - "DeleteVpnConnection": { - "methods": [ - "delete_vpn_connection" - ] - }, - "GenerateAccessToken": { - "methods": [ - "generate_access_token" - ] - }, - "GenerateOfflineCredential": { - "methods": [ - "generate_offline_credential" - ] - }, - "GetCluster": { - "methods": [ - "get_cluster" - ] - }, - "GetMachine": { - "methods": [ - "get_machine" - ] - }, - "GetNodePool": { - "methods": [ - "get_node_pool" - ] - }, - "GetServerConfig": { - "methods": [ - "get_server_config" - ] - }, - "GetVpnConnection": { - "methods": [ - "get_vpn_connection" - ] - }, - "ListClusters": { - "methods": [ - "list_clusters" - ] - }, - "ListMachines": { - "methods": [ - "list_machines" - ] - }, - "ListNodePools": { - "methods": [ - "list_node_pools" - ] - }, - "ListVpnConnections": { - "methods": [ - "list_vpn_connections" - ] - }, - "UpdateCluster": { - "methods": [ - "update_cluster" - ] - }, - "UpdateNodePool": { - "methods": [ - "update_node_pool" - ] - }, - "UpgradeCluster": { - "methods": [ - "upgrade_cluster" - ] - } - } - }, - "grpc-async": { - "libraryClient": "EdgeContainerAsyncClient", - "rpcs": { - "CreateCluster": { - "methods": [ - "create_cluster" - ] - }, - "CreateNodePool": { - "methods": [ - "create_node_pool" - ] - }, - "CreateVpnConnection": { - "methods": [ - "create_vpn_connection" - ] - }, - "DeleteCluster": { - "methods": [ - "delete_cluster" - ] - }, - "DeleteNodePool": { - "methods": [ - "delete_node_pool" - ] - }, - "DeleteVpnConnection": { - "methods": [ - "delete_vpn_connection" - ] - }, - "GenerateAccessToken": { - "methods": [ - "generate_access_token" - ] - }, - "GenerateOfflineCredential": { - "methods": [ - "generate_offline_credential" - ] - }, - "GetCluster": { - "methods": [ - "get_cluster" - ] - }, - "GetMachine": { - "methods": [ - "get_machine" - ] - }, - "GetNodePool": { - "methods": [ - "get_node_pool" - ] - }, - "GetServerConfig": { - "methods": [ - "get_server_config" - ] - }, - "GetVpnConnection": { - "methods": [ - "get_vpn_connection" - ] - }, - "ListClusters": { - "methods": [ - "list_clusters" - ] - }, - "ListMachines": { - "methods": [ - "list_machines" - ] - }, - "ListNodePools": { - "methods": [ - "list_node_pools" - ] - }, - "ListVpnConnections": { - "methods": [ - "list_vpn_connections" - ] - }, - "UpdateCluster": { - "methods": [ - "update_cluster" - ] - }, - "UpdateNodePool": { - "methods": [ - "update_node_pool" - ] - }, - "UpgradeCluster": { - "methods": [ - "upgrade_cluster" - ] - } - } - }, - "rest": { - "libraryClient": "EdgeContainerClient", - "rpcs": { - "CreateCluster": { - "methods": [ - "create_cluster" - ] - }, - "CreateNodePool": { - "methods": [ - "create_node_pool" - ] - }, - "CreateVpnConnection": { - "methods": [ - "create_vpn_connection" - ] - }, - "DeleteCluster": { - "methods": [ - "delete_cluster" - ] - }, - "DeleteNodePool": { - "methods": [ - "delete_node_pool" - ] - }, - "DeleteVpnConnection": { - "methods": [ - "delete_vpn_connection" - ] - }, - "GenerateAccessToken": { - "methods": [ - "generate_access_token" - ] - }, - "GenerateOfflineCredential": { - "methods": [ - "generate_offline_credential" - ] - }, - "GetCluster": { - "methods": [ - "get_cluster" - ] - }, - "GetMachine": { - "methods": [ - "get_machine" - ] - }, - "GetNodePool": { - "methods": [ - "get_node_pool" - ] - }, - "GetServerConfig": { - "methods": [ - "get_server_config" - ] - }, - "GetVpnConnection": { - "methods": [ - "get_vpn_connection" - ] - }, - "ListClusters": { - "methods": [ - "list_clusters" - ] - }, - "ListMachines": { - "methods": [ - "list_machines" - ] - }, - "ListNodePools": { - "methods": [ - "list_node_pools" - ] - }, - "ListVpnConnections": { - "methods": [ - "list_vpn_connections" - ] - }, - "UpdateCluster": { - "methods": [ - "update_cluster" - ] - }, - "UpdateNodePool": { - "methods": [ - "update_node_pool" - ] - }, - "UpgradeCluster": { - "methods": [ - "upgrade_cluster" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/google-cloud-edgecontainer/v1/google/cloud/edgecontainer_v1/gapic_version.py b/owl-bot-staging/google-cloud-edgecontainer/v1/google/cloud/edgecontainer_v1/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-cloud-edgecontainer/v1/google/cloud/edgecontainer_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-edgecontainer/v1/google/cloud/edgecontainer_v1/py.typed b/owl-bot-staging/google-cloud-edgecontainer/v1/google/cloud/edgecontainer_v1/py.typed deleted file mode 100644 index b447eeb1b655..000000000000 --- a/owl-bot-staging/google-cloud-edgecontainer/v1/google/cloud/edgecontainer_v1/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-edgecontainer package uses inline types. diff --git a/owl-bot-staging/google-cloud-edgecontainer/v1/google/cloud/edgecontainer_v1/services/__init__.py b/owl-bot-staging/google-cloud-edgecontainer/v1/google/cloud/edgecontainer_v1/services/__init__.py deleted file mode 100644 index 8f6cf068242c..000000000000 --- a/owl-bot-staging/google-cloud-edgecontainer/v1/google/cloud/edgecontainer_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-edgecontainer/v1/google/cloud/edgecontainer_v1/services/edge_container/__init__.py b/owl-bot-staging/google-cloud-edgecontainer/v1/google/cloud/edgecontainer_v1/services/edge_container/__init__.py deleted file mode 100644 index 3b21db5e7692..000000000000 --- a/owl-bot-staging/google-cloud-edgecontainer/v1/google/cloud/edgecontainer_v1/services/edge_container/__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 EdgeContainerClient -from .async_client import EdgeContainerAsyncClient - -__all__ = ( - 'EdgeContainerClient', - 'EdgeContainerAsyncClient', -) diff --git a/owl-bot-staging/google-cloud-edgecontainer/v1/google/cloud/edgecontainer_v1/services/edge_container/async_client.py b/owl-bot-staging/google-cloud-edgecontainer/v1/google/cloud/edgecontainer_v1/services/edge_container/async_client.py deleted file mode 100644 index 2d4a00abdc97..000000000000 --- a/owl-bot-staging/google-cloud-edgecontainer/v1/google/cloud/edgecontainer_v1/services/edge_container/async_client.py +++ /dev/null @@ -1,2931 +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 re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.edgecontainer_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_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.edgecontainer_v1.services.edge_container import pagers -from google.cloud.edgecontainer_v1.types import resources -from google.cloud.edgecontainer_v1.types import service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import EdgeContainerTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import EdgeContainerGrpcAsyncIOTransport -from .client import EdgeContainerClient - - -class EdgeContainerAsyncClient: - """EdgeContainer API provides management of Kubernetes Clusters - on Google Edge Cloud deployments. - """ - - _client: EdgeContainerClient - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = EdgeContainerClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = EdgeContainerClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = EdgeContainerClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = EdgeContainerClient._DEFAULT_UNIVERSE - - cluster_path = staticmethod(EdgeContainerClient.cluster_path) - parse_cluster_path = staticmethod(EdgeContainerClient.parse_cluster_path) - crypto_key_path = staticmethod(EdgeContainerClient.crypto_key_path) - parse_crypto_key_path = staticmethod(EdgeContainerClient.parse_crypto_key_path) - crypto_key_version_path = staticmethod(EdgeContainerClient.crypto_key_version_path) - parse_crypto_key_version_path = staticmethod(EdgeContainerClient.parse_crypto_key_version_path) - machine_path = staticmethod(EdgeContainerClient.machine_path) - parse_machine_path = staticmethod(EdgeContainerClient.parse_machine_path) - node_pool_path = staticmethod(EdgeContainerClient.node_pool_path) - parse_node_pool_path = staticmethod(EdgeContainerClient.parse_node_pool_path) - vpn_connection_path = staticmethod(EdgeContainerClient.vpn_connection_path) - parse_vpn_connection_path = staticmethod(EdgeContainerClient.parse_vpn_connection_path) - common_billing_account_path = staticmethod(EdgeContainerClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(EdgeContainerClient.parse_common_billing_account_path) - common_folder_path = staticmethod(EdgeContainerClient.common_folder_path) - parse_common_folder_path = staticmethod(EdgeContainerClient.parse_common_folder_path) - common_organization_path = staticmethod(EdgeContainerClient.common_organization_path) - parse_common_organization_path = staticmethod(EdgeContainerClient.parse_common_organization_path) - common_project_path = staticmethod(EdgeContainerClient.common_project_path) - parse_common_project_path = staticmethod(EdgeContainerClient.parse_common_project_path) - common_location_path = staticmethod(EdgeContainerClient.common_location_path) - parse_common_location_path = staticmethod(EdgeContainerClient.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: - EdgeContainerAsyncClient: The constructed client. - """ - return EdgeContainerClient.from_service_account_info.__func__(EdgeContainerAsyncClient, 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: - EdgeContainerAsyncClient: The constructed client. - """ - return EdgeContainerClient.from_service_account_file.__func__(EdgeContainerAsyncClient, 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 EdgeContainerClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> EdgeContainerTransport: - """Returns the transport used by the client instance. - - Returns: - EdgeContainerTransport: 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 = EdgeContainerClient.get_transport_class - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, EdgeContainerTransport, Callable[..., EdgeContainerTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the edge container 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,EdgeContainerTransport,Callable[..., EdgeContainerTransport]]]): - 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 EdgeContainerTransport 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 = EdgeContainerClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def list_clusters(self, - request: Optional[Union[service.ListClustersRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListClustersAsyncPager: - r"""Lists Clusters in a given project and location. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import edgecontainer_v1 - - async def sample_list_clusters(): - # Create a client - client = edgecontainer_v1.EdgeContainerAsyncClient() - - # Initialize request argument(s) - request = edgecontainer_v1.ListClustersRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_clusters(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.edgecontainer_v1.types.ListClustersRequest, dict]]): - The request object. Lists clusters in a location. - parent (:class:`str`): - Required. The parent location, which - owns this collection of clusters. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.edgecontainer_v1.services.edge_container.pagers.ListClustersAsyncPager: - List of clusters in a location. - - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, service.ListClustersRequest): - request = service.ListClustersRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.list_clusters] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListClustersAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_cluster(self, - request: Optional[Union[service.GetClusterRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.Cluster: - r"""Gets details of a single Cluster. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import edgecontainer_v1 - - async def sample_get_cluster(): - # Create a client - client = edgecontainer_v1.EdgeContainerAsyncClient() - - # Initialize request argument(s) - request = edgecontainer_v1.GetClusterRequest( - name="name_value", - ) - - # Make the request - response = await client.get_cluster(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.edgecontainer_v1.types.GetClusterRequest, dict]]): - The request object. Gets a cluster. - name (:class:`str`): - Required. The resource name of the - cluster. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.edgecontainer_v1.types.Cluster: - A Google Distributed Cloud Edge - Kubernetes cluster. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, service.GetClusterRequest): - request = service.GetClusterRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.get_cluster] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_cluster(self, - request: Optional[Union[service.CreateClusterRequest, dict]] = None, - *, - parent: Optional[str] = None, - cluster: Optional[resources.Cluster] = None, - cluster_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Creates a new Cluster in a given project and - location. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import edgecontainer_v1 - - async def sample_create_cluster(): - # Create a client - client = edgecontainer_v1.EdgeContainerAsyncClient() - - # Initialize request argument(s) - cluster = edgecontainer_v1.Cluster() - cluster.name = "name_value" - cluster.fleet.project = "project_value" - cluster.networking.cluster_ipv4_cidr_blocks = ['cluster_ipv4_cidr_blocks_value1', 'cluster_ipv4_cidr_blocks_value2'] - cluster.networking.services_ipv4_cidr_blocks = ['services_ipv4_cidr_blocks_value1', 'services_ipv4_cidr_blocks_value2'] - cluster.authorization.admin_users.username = "username_value" - - request = edgecontainer_v1.CreateClusterRequest( - parent="parent_value", - cluster_id="cluster_id_value", - cluster=cluster, - ) - - # Make the request - operation = client.create_cluster(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.edgecontainer_v1.types.CreateClusterRequest, dict]]): - The request object. Creates a cluster. - parent (:class:`str`): - Required. The parent location where - this cluster will be created. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - cluster (:class:`google.cloud.edgecontainer_v1.types.Cluster`): - Required. The cluster to create. - This corresponds to the ``cluster`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - cluster_id (:class:`str`): - Required. A client-specified unique - identifier for the cluster. - - This corresponds to the ``cluster_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.edgecontainer_v1.types.Cluster` A - Google Distributed Cloud Edge Kubernetes cluster. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, cluster, cluster_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, service.CreateClusterRequest): - request = service.CreateClusterRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if cluster is not None: - request.cluster = cluster - if cluster_id is not None: - request.cluster_id = cluster_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_cluster] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - resources.Cluster, - metadata_type=service.OperationMetadata, - ) - - # Done; return the response. - return response - - async def update_cluster(self, - request: Optional[Union[service.UpdateClusterRequest, dict]] = None, - *, - cluster: Optional[resources.Cluster] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Updates the parameters of a single Cluster. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import edgecontainer_v1 - - async def sample_update_cluster(): - # Create a client - client = edgecontainer_v1.EdgeContainerAsyncClient() - - # Initialize request argument(s) - request = edgecontainer_v1.UpdateClusterRequest( - ) - - # Make the request - operation = client.update_cluster(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.edgecontainer_v1.types.UpdateClusterRequest, dict]]): - The request object. Updates a cluster. - cluster (:class:`google.cloud.edgecontainer_v1.types.Cluster`): - The updated cluster. - This corresponds to the ``cluster`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Field mask is used to specify the fields to be - overwritten in the Cluster resource by the update. The - fields specified in the update_mask are relative to the - resource, not the full request. A field will be - overwritten if it is in the mask. If the user does not - provide a mask then all fields will be overwritten. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.edgecontainer_v1.types.Cluster` A - Google Distributed Cloud Edge Kubernetes cluster. - - """ - # Create or coerce a 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([cluster, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, service.UpdateClusterRequest): - request = service.UpdateClusterRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if cluster is not None: - request.cluster = cluster - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_cluster] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("cluster.name", request.cluster.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.Cluster, - metadata_type=service.OperationMetadata, - ) - - # Done; return the response. - return response - - async def upgrade_cluster(self, - request: Optional[Union[service.UpgradeClusterRequest, dict]] = None, - *, - name: Optional[str] = None, - target_version: Optional[str] = None, - schedule: Optional[service.UpgradeClusterRequest.Schedule] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Upgrades a single cluster. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import edgecontainer_v1 - - async def sample_upgrade_cluster(): - # Create a client - client = edgecontainer_v1.EdgeContainerAsyncClient() - - # Initialize request argument(s) - request = edgecontainer_v1.UpgradeClusterRequest( - name="name_value", - target_version="target_version_value", - ) - - # Make the request - operation = client.upgrade_cluster(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.edgecontainer_v1.types.UpgradeClusterRequest, dict]]): - The request object. Upgrades a cluster. - name (:class:`str`): - Required. The resource name of the - cluster. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - target_version (:class:`str`): - Required. The version the cluster is - going to be upgraded to. - - This corresponds to the ``target_version`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - schedule (:class:`google.cloud.edgecontainer_v1.types.UpgradeClusterRequest.Schedule`): - The schedule for the upgrade. - This corresponds to the ``schedule`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.edgecontainer_v1.types.Cluster` A - Google Distributed Cloud Edge Kubernetes cluster. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, target_version, schedule]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, service.UpgradeClusterRequest): - request = service.UpgradeClusterRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if target_version is not None: - request.target_version = target_version - if schedule is not None: - request.schedule = schedule - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.upgrade_cluster] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - resources.Cluster, - metadata_type=service.OperationMetadata, - ) - - # Done; return the response. - return response - - async def delete_cluster(self, - request: Optional[Union[service.DeleteClusterRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Deletes a single Cluster. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import edgecontainer_v1 - - async def sample_delete_cluster(): - # Create a client - client = edgecontainer_v1.EdgeContainerAsyncClient() - - # Initialize request argument(s) - request = edgecontainer_v1.DeleteClusterRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_cluster(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.edgecontainer_v1.types.DeleteClusterRequest, dict]]): - The request object. Deletes a cluster. - name (:class:`str`): - Required. The resource name of the - cluster. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.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([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, service.DeleteClusterRequest): - request = service.DeleteClusterRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.delete_cluster] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - empty_pb2.Empty, - metadata_type=service.OperationMetadata, - ) - - # Done; return the response. - return response - - async def generate_access_token(self, - request: Optional[Union[service.GenerateAccessTokenRequest, dict]] = None, - *, - cluster: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> service.GenerateAccessTokenResponse: - r"""Generates an access token for a Cluster. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import edgecontainer_v1 - - async def sample_generate_access_token(): - # Create a client - client = edgecontainer_v1.EdgeContainerAsyncClient() - - # Initialize request argument(s) - request = edgecontainer_v1.GenerateAccessTokenRequest( - cluster="cluster_value", - ) - - # Make the request - response = await client.generate_access_token(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.edgecontainer_v1.types.GenerateAccessTokenRequest, dict]]): - The request object. Generates an access token for a - cluster. - cluster (:class:`str`): - Required. The resource name of the - cluster. - - This corresponds to the ``cluster`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.edgecontainer_v1.types.GenerateAccessTokenResponse: - An access token for a cluster. - """ - # Create or coerce a 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([cluster]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, service.GenerateAccessTokenRequest): - request = service.GenerateAccessTokenRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if cluster is not None: - request.cluster = cluster - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.generate_access_token] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("cluster", request.cluster), - )), - ) - - # 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 generate_offline_credential(self, - request: Optional[Union[service.GenerateOfflineCredentialRequest, dict]] = None, - *, - cluster: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> service.GenerateOfflineCredentialResponse: - r"""Generates an offline credential for a Cluster. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import edgecontainer_v1 - - async def sample_generate_offline_credential(): - # Create a client - client = edgecontainer_v1.EdgeContainerAsyncClient() - - # Initialize request argument(s) - request = edgecontainer_v1.GenerateOfflineCredentialRequest( - cluster="cluster_value", - ) - - # Make the request - response = await client.generate_offline_credential(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.edgecontainer_v1.types.GenerateOfflineCredentialRequest, dict]]): - The request object. Generates an offline - credential(offline) for a cluster. - cluster (:class:`str`): - Required. The resource name of the - cluster. - - This corresponds to the ``cluster`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.edgecontainer_v1.types.GenerateOfflineCredentialResponse: - An offline credential for a cluster. - """ - # Create or coerce a 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([cluster]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, service.GenerateOfflineCredentialRequest): - request = service.GenerateOfflineCredentialRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if cluster is not None: - request.cluster = cluster - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.generate_offline_credential] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("cluster", request.cluster), - )), - ) - - # 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_node_pools(self, - request: Optional[Union[service.ListNodePoolsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListNodePoolsAsyncPager: - r"""Lists NodePools in a given project and location. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import edgecontainer_v1 - - async def sample_list_node_pools(): - # Create a client - client = edgecontainer_v1.EdgeContainerAsyncClient() - - # Initialize request argument(s) - request = edgecontainer_v1.ListNodePoolsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_node_pools(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.edgecontainer_v1.types.ListNodePoolsRequest, dict]]): - The request object. Lists node pools in a cluster. - parent (:class:`str`): - Required. The parent cluster, which - owns this collection of node pools. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.edgecontainer_v1.services.edge_container.pagers.ListNodePoolsAsyncPager: - List of node pools in a cluster. - - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, service.ListNodePoolsRequest): - request = service.ListNodePoolsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.list_node_pools] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListNodePoolsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_node_pool(self, - request: Optional[Union[service.GetNodePoolRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.NodePool: - r"""Gets details of a single NodePool. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import edgecontainer_v1 - - async def sample_get_node_pool(): - # Create a client - client = edgecontainer_v1.EdgeContainerAsyncClient() - - # Initialize request argument(s) - request = edgecontainer_v1.GetNodePoolRequest( - name="name_value", - ) - - # Make the request - response = await client.get_node_pool(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.edgecontainer_v1.types.GetNodePoolRequest, dict]]): - The request object. Gets a node pool. - name (:class:`str`): - Required. The resource name of the - node pool. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.edgecontainer_v1.types.NodePool: - A set of Kubernetes nodes in a - cluster with common configuration and - specification. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, service.GetNodePoolRequest): - request = service.GetNodePoolRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.get_node_pool] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_node_pool(self, - request: Optional[Union[service.CreateNodePoolRequest, dict]] = None, - *, - parent: Optional[str] = None, - node_pool: Optional[resources.NodePool] = None, - node_pool_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Creates a new NodePool in a given project and - location. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import edgecontainer_v1 - - async def sample_create_node_pool(): - # Create a client - client = edgecontainer_v1.EdgeContainerAsyncClient() - - # Initialize request argument(s) - node_pool = edgecontainer_v1.NodePool() - node_pool.name = "name_value" - node_pool.node_count = 1070 - - request = edgecontainer_v1.CreateNodePoolRequest( - parent="parent_value", - node_pool_id="node_pool_id_value", - node_pool=node_pool, - ) - - # Make the request - operation = client.create_node_pool(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.edgecontainer_v1.types.CreateNodePoolRequest, dict]]): - The request object. Creates a node pool. - parent (:class:`str`): - Required. The parent cluster where - this node pool will be created. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - node_pool (:class:`google.cloud.edgecontainer_v1.types.NodePool`): - Required. The node pool to create. - This corresponds to the ``node_pool`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - node_pool_id (:class:`str`): - Required. A client-specified unique - identifier for the node pool. - - This corresponds to the ``node_pool_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.edgecontainer_v1.types.NodePool` A set of Kubernetes nodes in a cluster with common configuration and - specification. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, node_pool, node_pool_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, service.CreateNodePoolRequest): - request = service.CreateNodePoolRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if node_pool is not None: - request.node_pool = node_pool - if node_pool_id is not None: - request.node_pool_id = node_pool_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_node_pool] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - resources.NodePool, - metadata_type=service.OperationMetadata, - ) - - # Done; return the response. - return response - - async def update_node_pool(self, - request: Optional[Union[service.UpdateNodePoolRequest, dict]] = None, - *, - node_pool: Optional[resources.NodePool] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Updates the parameters of a single NodePool. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import edgecontainer_v1 - - async def sample_update_node_pool(): - # Create a client - client = edgecontainer_v1.EdgeContainerAsyncClient() - - # Initialize request argument(s) - request = edgecontainer_v1.UpdateNodePoolRequest( - ) - - # Make the request - operation = client.update_node_pool(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.edgecontainer_v1.types.UpdateNodePoolRequest, dict]]): - The request object. Updates a node pool. - node_pool (:class:`google.cloud.edgecontainer_v1.types.NodePool`): - The updated node pool. - This corresponds to the ``node_pool`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Field mask is used to specify the fields to be - overwritten in the NodePool resource by the update. The - fields specified in the update_mask are relative to the - resource, not the full request. A field will be - overwritten if it is in the mask. If the user does not - provide a mask then all fields will be overwritten. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.edgecontainer_v1.types.NodePool` A set of Kubernetes nodes in a cluster with common configuration and - specification. - - """ - # Create or coerce a 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([node_pool, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, service.UpdateNodePoolRequest): - request = service.UpdateNodePoolRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if node_pool is not None: - request.node_pool = node_pool - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_node_pool] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("node_pool.name", request.node_pool.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.NodePool, - metadata_type=service.OperationMetadata, - ) - - # Done; return the response. - return response - - async def delete_node_pool(self, - request: Optional[Union[service.DeleteNodePoolRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Deletes a single NodePool. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import edgecontainer_v1 - - async def sample_delete_node_pool(): - # Create a client - client = edgecontainer_v1.EdgeContainerAsyncClient() - - # Initialize request argument(s) - request = edgecontainer_v1.DeleteNodePoolRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_node_pool(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.edgecontainer_v1.types.DeleteNodePoolRequest, dict]]): - The request object. Deletes a node pool. - name (:class:`str`): - Required. The resource name of the - node pool. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.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([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, service.DeleteNodePoolRequest): - request = service.DeleteNodePoolRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.delete_node_pool] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - empty_pb2.Empty, - metadata_type=service.OperationMetadata, - ) - - # Done; return the response. - return response - - async def list_machines(self, - request: Optional[Union[service.ListMachinesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListMachinesAsyncPager: - r"""Lists Machines in a given project and location. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import edgecontainer_v1 - - async def sample_list_machines(): - # Create a client - client = edgecontainer_v1.EdgeContainerAsyncClient() - - # Initialize request argument(s) - request = edgecontainer_v1.ListMachinesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_machines(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.edgecontainer_v1.types.ListMachinesRequest, dict]]): - The request object. Lists machines in a site. - parent (:class:`str`): - Required. The parent site, which owns - this collection of machines. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.edgecontainer_v1.services.edge_container.pagers.ListMachinesAsyncPager: - List of machines in a site. - - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, service.ListMachinesRequest): - request = service.ListMachinesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.list_machines] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListMachinesAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_machine(self, - request: Optional[Union[service.GetMachineRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.Machine: - r"""Gets details of a single Machine. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import edgecontainer_v1 - - async def sample_get_machine(): - # Create a client - client = edgecontainer_v1.EdgeContainerAsyncClient() - - # Initialize request argument(s) - request = edgecontainer_v1.GetMachineRequest( - name="name_value", - ) - - # Make the request - response = await client.get_machine(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.edgecontainer_v1.types.GetMachineRequest, dict]]): - The request object. Gets a machine. - name (:class:`str`): - Required. The resource name of the - machine. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.edgecontainer_v1.types.Machine: - A Google Distributed Cloud Edge - machine capable of acting as a - Kubernetes node. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, service.GetMachineRequest): - request = service.GetMachineRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.get_machine] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_vpn_connections(self, - request: Optional[Union[service.ListVpnConnectionsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListVpnConnectionsAsyncPager: - r"""Lists VPN connections in a given project and - location. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import edgecontainer_v1 - - async def sample_list_vpn_connections(): - # Create a client - client = edgecontainer_v1.EdgeContainerAsyncClient() - - # Initialize request argument(s) - request = edgecontainer_v1.ListVpnConnectionsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_vpn_connections(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.edgecontainer_v1.types.ListVpnConnectionsRequest, dict]]): - The request object. Lists VPN connections. - parent (:class:`str`): - Required. The parent location, which - owns this collection of VPN connections. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.edgecontainer_v1.services.edge_container.pagers.ListVpnConnectionsAsyncPager: - List of VPN connections in a - location. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, service.ListVpnConnectionsRequest): - request = service.ListVpnConnectionsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.list_vpn_connections] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListVpnConnectionsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_vpn_connection(self, - request: Optional[Union[service.GetVpnConnectionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.VpnConnection: - r"""Gets details of a single VPN connection. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import edgecontainer_v1 - - async def sample_get_vpn_connection(): - # Create a client - client = edgecontainer_v1.EdgeContainerAsyncClient() - - # Initialize request argument(s) - request = edgecontainer_v1.GetVpnConnectionRequest( - name="name_value", - ) - - # Make the request - response = await client.get_vpn_connection(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.edgecontainer_v1.types.GetVpnConnectionRequest, dict]]): - The request object. Gets a VPN connection. - name (:class:`str`): - Required. The resource name of the - vpn connection. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.edgecontainer_v1.types.VpnConnection: - A VPN connection . - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, service.GetVpnConnectionRequest): - request = service.GetVpnConnectionRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.get_vpn_connection] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_vpn_connection(self, - request: Optional[Union[service.CreateVpnConnectionRequest, dict]] = None, - *, - parent: Optional[str] = None, - vpn_connection: Optional[resources.VpnConnection] = None, - vpn_connection_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Creates a new VPN connection in a given project and - location. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import edgecontainer_v1 - - async def sample_create_vpn_connection(): - # Create a client - client = edgecontainer_v1.EdgeContainerAsyncClient() - - # Initialize request argument(s) - vpn_connection = edgecontainer_v1.VpnConnection() - vpn_connection.name = "name_value" - - request = edgecontainer_v1.CreateVpnConnectionRequest( - parent="parent_value", - vpn_connection_id="vpn_connection_id_value", - vpn_connection=vpn_connection, - ) - - # Make the request - operation = client.create_vpn_connection(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.edgecontainer_v1.types.CreateVpnConnectionRequest, dict]]): - The request object. Creates a VPN connection. - parent (:class:`str`): - Required. The parent location where - this vpn connection will be created. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - vpn_connection (:class:`google.cloud.edgecontainer_v1.types.VpnConnection`): - Required. The VPN connection to - create. - - This corresponds to the ``vpn_connection`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - vpn_connection_id (:class:`str`): - Required. The VPN connection - identifier. - - This corresponds to the ``vpn_connection_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.edgecontainer_v1.types.VpnConnection` - A VPN connection . - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, vpn_connection, vpn_connection_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, service.CreateVpnConnectionRequest): - request = service.CreateVpnConnectionRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if vpn_connection is not None: - request.vpn_connection = vpn_connection - if vpn_connection_id is not None: - request.vpn_connection_id = vpn_connection_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_vpn_connection] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - resources.VpnConnection, - metadata_type=service.OperationMetadata, - ) - - # Done; return the response. - return response - - async def delete_vpn_connection(self, - request: Optional[Union[service.DeleteVpnConnectionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Deletes a single VPN connection. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import edgecontainer_v1 - - async def sample_delete_vpn_connection(): - # Create a client - client = edgecontainer_v1.EdgeContainerAsyncClient() - - # Initialize request argument(s) - request = edgecontainer_v1.DeleteVpnConnectionRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_vpn_connection(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.edgecontainer_v1.types.DeleteVpnConnectionRequest, dict]]): - The request object. Deletes a vpn connection. - name (:class:`str`): - Required. The resource name of the - vpn connection. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.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([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, service.DeleteVpnConnectionRequest): - request = service.DeleteVpnConnectionRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.delete_vpn_connection] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - empty_pb2.Empty, - metadata_type=service.OperationMetadata, - ) - - # Done; return the response. - return response - - async def get_server_config(self, - request: Optional[Union[service.GetServerConfigRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.ServerConfig: - r"""Gets the server config. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import edgecontainer_v1 - - async def sample_get_server_config(): - # Create a client - client = edgecontainer_v1.EdgeContainerAsyncClient() - - # Initialize request argument(s) - request = edgecontainer_v1.GetServerConfigRequest( - name="name_value", - ) - - # Make the request - response = await client.get_server_config(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.edgecontainer_v1.types.GetServerConfigRequest, dict]]): - The request object. Gets the server config. - name (:class:`str`): - Required. The name (project and location) of the server - config to get, specified in the format - ``projects/*/locations/*``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.edgecontainer_v1.types.ServerConfig: - Server configuration for supported - versions and release channels. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, service.GetServerConfigRequest): - request = service.GetServerConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.get_server_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self.transport._wrapped_methods[self._client._transport.list_operations] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self.transport._wrapped_methods[self._client._transport.get_operation] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def delete_operation( - self, - request: Optional[operations_pb2.DeleteOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a long-running operation. - - This method indicates that the client is no longer interested - in the operation result. It does not cancel the operation. - If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.DeleteOperationRequest`): - The request object. Request message for - `DeleteOperation` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.DeleteOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self.transport._wrapped_methods[self._client._transport.delete_operation] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - async def cancel_operation( - self, - request: Optional[operations_pb2.CancelOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.CancelOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self.transport._wrapped_methods[self._client._transport.cancel_operation] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - async def get_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.GetLocationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self.transport._wrapped_methods[self._client._transport.get_location] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def list_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.ListLocationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self.transport._wrapped_methods[self._client._transport.list_locations] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def __aenter__(self) -> "EdgeContainerAsyncClient": - 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__ = ( - "EdgeContainerAsyncClient", -) diff --git a/owl-bot-staging/google-cloud-edgecontainer/v1/google/cloud/edgecontainer_v1/services/edge_container/client.py b/owl-bot-staging/google-cloud-edgecontainer/v1/google/cloud/edgecontainer_v1/services/edge_container/client.py deleted file mode 100644 index 7344834691cf..000000000000 --- a/owl-bot-staging/google-cloud-edgecontainer/v1/google/cloud/edgecontainer_v1/services/edge_container/client.py +++ /dev/null @@ -1,3308 +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 os -import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast -import warnings - -from google.cloud.edgecontainer_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 - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.edgecontainer_v1.services.edge_container import pagers -from google.cloud.edgecontainer_v1.types import resources -from google.cloud.edgecontainer_v1.types import service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import EdgeContainerTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import EdgeContainerGrpcTransport -from .transports.grpc_asyncio import EdgeContainerGrpcAsyncIOTransport -from .transports.rest import EdgeContainerRestTransport - - -class EdgeContainerClientMeta(type): - """Metaclass for the EdgeContainer 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[EdgeContainerTransport]] - _transport_registry["grpc"] = EdgeContainerGrpcTransport - _transport_registry["grpc_asyncio"] = EdgeContainerGrpcAsyncIOTransport - _transport_registry["rest"] = EdgeContainerRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[EdgeContainerTransport]: - """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 EdgeContainerClient(metaclass=EdgeContainerClientMeta): - """EdgeContainer API provides management of Kubernetes Clusters - on Google Edge Cloud deployments. - """ - - @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 = "edgecontainer.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - _DEFAULT_ENDPOINT_TEMPLATE = "edgecontainer.{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: - EdgeContainerClient: 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: - EdgeContainerClient: 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) -> EdgeContainerTransport: - """Returns the transport used by the client instance. - - Returns: - EdgeContainerTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def cluster_path(project: str,location: str,cluster: str,) -> str: - """Returns a fully-qualified cluster string.""" - return "projects/{project}/locations/{location}/clusters/{cluster}".format(project=project, location=location, cluster=cluster, ) - - @staticmethod - def parse_cluster_path(path: str) -> Dict[str,str]: - """Parses a cluster path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/clusters/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def crypto_key_path(project: str,location: str,key_ring: str,crypto_key: str,) -> str: - """Returns a fully-qualified crypto_key string.""" - return "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}".format(project=project, location=location, key_ring=key_ring, crypto_key=crypto_key, ) - - @staticmethod - def parse_crypto_key_path(path: str) -> Dict[str,str]: - """Parses a crypto_key path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/keyRings/(?P.+?)/cryptoKeys/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def crypto_key_version_path(project: str,location: str,key_ring: str,crypto_key: str,crypto_key_version: str,) -> str: - """Returns a fully-qualified crypto_key_version string.""" - return "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}/cryptoKeyVersions/{crypto_key_version}".format(project=project, location=location, key_ring=key_ring, crypto_key=crypto_key, crypto_key_version=crypto_key_version, ) - - @staticmethod - def parse_crypto_key_version_path(path: str) -> Dict[str,str]: - """Parses a crypto_key_version path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/keyRings/(?P.+?)/cryptoKeys/(?P.+?)/cryptoKeyVersions/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def machine_path(project: str,location: str,machine: str,) -> str: - """Returns a fully-qualified machine string.""" - return "projects/{project}/locations/{location}/machines/{machine}".format(project=project, location=location, machine=machine, ) - - @staticmethod - def parse_machine_path(path: str) -> Dict[str,str]: - """Parses a machine path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/machines/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def node_pool_path(project: str,location: str,cluster: str,node_pool: str,) -> str: - """Returns a fully-qualified node_pool string.""" - return "projects/{project}/locations/{location}/clusters/{cluster}/nodePools/{node_pool}".format(project=project, location=location, cluster=cluster, node_pool=node_pool, ) - - @staticmethod - def parse_node_pool_path(path: str) -> Dict[str,str]: - """Parses a node_pool path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/clusters/(?P.+?)/nodePools/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def vpn_connection_path(project: str,location: str,vpn_connection: str,) -> str: - """Returns a fully-qualified vpn_connection string.""" - return "projects/{project}/locations/{location}/vpnConnections/{vpn_connection}".format(project=project, location=location, vpn_connection=vpn_connection, ) - - @staticmethod - def parse_vpn_connection_path(path: str) -> Dict[str,str]: - """Parses a vpn_connection path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/vpnConnections/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Deprecated. Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - - warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", - DeprecationWarning) - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - @staticmethod - def _read_environment_variables(): - """Returns the environment variables used by the client. - - Returns: - Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, - GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. - - Raises: - ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not - any of ["true", "false"]. - google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT - is not any of ["auto", "never", "always"]. - """ - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() - universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env - - @staticmethod - def _get_client_cert_source(provided_cert_source, use_cert_flag): - """Return the client cert source to be used by the client. - - Args: - provided_cert_source (bytes): The client certificate source provided. - use_cert_flag (bool): A flag indicating whether to use the client certificate. - - Returns: - bytes or None: The client cert source to be used by the client. - """ - client_cert_source = None - if use_cert_flag: - if provided_cert_source: - client_cert_source = provided_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - return client_cert_source - - @staticmethod - def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint): - """Return the API endpoint used by the client. - - Args: - api_override (str): The API endpoint override. If specified, this is always - the return value of this function and the other arguments are not used. - client_cert_source (bytes): The client certificate source used by the client. - universe_domain (str): The universe domain used by the client. - use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. - Possible values are "always", "auto", or "never". - - Returns: - str: The API endpoint to be used by the client. - """ - if api_override is not None: - api_endpoint = api_override - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - _default_universe = EdgeContainerClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = EdgeContainerClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = EdgeContainerClient._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 = EdgeContainerClient._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 - - @staticmethod - def _compare_universes(client_universe: str, - credentials: ga_credentials.Credentials) -> bool: - """Returns True iff the universe domains used by the client and credentials match. - - Args: - client_universe (str): The universe domain configured via the client options. - credentials (ga_credentials.Credentials): The credentials being used in the client. - - Returns: - bool: True iff client_universe matches the universe in credentials. - - Raises: - ValueError: when client_universe does not match the universe in credentials. - """ - - default_universe = EdgeContainerClient._DEFAULT_UNIVERSE - credentials_universe = getattr(credentials, "universe_domain", default_universe) - - if client_universe != credentials_universe: - raise ValueError("The configured universe domain " - f"({client_universe}) does not match the universe domain " - f"found in the credentials ({credentials_universe}). " - "If you haven't configured the universe domain explicitly, " - f"`{default_universe}` is the default.") - return True - - 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. - """ - self._is_universe_domain_valid = (self._is_universe_domain_valid or - EdgeContainerClient._compare_universes(self.universe_domain, self.transport._credentials)) - return self._is_universe_domain_valid - - @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, EdgeContainerTransport, Callable[..., EdgeContainerTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the edge container 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,EdgeContainerTransport,Callable[..., EdgeContainerTransport]]]): - 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 EdgeContainerTransport 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 = EdgeContainerClient._read_environment_variables() - self._client_cert_source = EdgeContainerClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = EdgeContainerClient._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 - - 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, EdgeContainerTransport) - if transport_provided: - # transport is a EdgeContainerTransport 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(EdgeContainerTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - EdgeContainerClient._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[EdgeContainerTransport], Callable[..., EdgeContainerTransport]] = ( - EdgeContainerClient.get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., EdgeContainerTransport], 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, - ) - - def list_clusters(self, - request: Optional[Union[service.ListClustersRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListClustersPager: - r"""Lists Clusters in a given project and location. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import edgecontainer_v1 - - def sample_list_clusters(): - # Create a client - client = edgecontainer_v1.EdgeContainerClient() - - # Initialize request argument(s) - request = edgecontainer_v1.ListClustersRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_clusters(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.edgecontainer_v1.types.ListClustersRequest, dict]): - The request object. Lists clusters in a location. - parent (str): - Required. The parent location, which - owns this collection of clusters. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.edgecontainer_v1.services.edge_container.pagers.ListClustersPager: - List of clusters in a location. - - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, service.ListClustersRequest): - request = service.ListClustersRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_clusters] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListClustersPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_cluster(self, - request: Optional[Union[service.GetClusterRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.Cluster: - r"""Gets details of a single Cluster. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import edgecontainer_v1 - - def sample_get_cluster(): - # Create a client - client = edgecontainer_v1.EdgeContainerClient() - - # Initialize request argument(s) - request = edgecontainer_v1.GetClusterRequest( - name="name_value", - ) - - # Make the request - response = client.get_cluster(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.edgecontainer_v1.types.GetClusterRequest, dict]): - The request object. Gets a cluster. - name (str): - Required. The resource name of the - cluster. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.edgecontainer_v1.types.Cluster: - A Google Distributed Cloud Edge - Kubernetes cluster. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, service.GetClusterRequest): - request = service.GetClusterRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_cluster] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def create_cluster(self, - request: Optional[Union[service.CreateClusterRequest, dict]] = None, - *, - parent: Optional[str] = None, - cluster: Optional[resources.Cluster] = None, - cluster_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Creates a new Cluster in a given project and - location. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import edgecontainer_v1 - - def sample_create_cluster(): - # Create a client - client = edgecontainer_v1.EdgeContainerClient() - - # Initialize request argument(s) - cluster = edgecontainer_v1.Cluster() - cluster.name = "name_value" - cluster.fleet.project = "project_value" - cluster.networking.cluster_ipv4_cidr_blocks = ['cluster_ipv4_cidr_blocks_value1', 'cluster_ipv4_cidr_blocks_value2'] - cluster.networking.services_ipv4_cidr_blocks = ['services_ipv4_cidr_blocks_value1', 'services_ipv4_cidr_blocks_value2'] - cluster.authorization.admin_users.username = "username_value" - - request = edgecontainer_v1.CreateClusterRequest( - parent="parent_value", - cluster_id="cluster_id_value", - cluster=cluster, - ) - - # Make the request - operation = client.create_cluster(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.edgecontainer_v1.types.CreateClusterRequest, dict]): - The request object. Creates a cluster. - parent (str): - Required. The parent location where - this cluster will be created. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - cluster (google.cloud.edgecontainer_v1.types.Cluster): - Required. The cluster to create. - This corresponds to the ``cluster`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - cluster_id (str): - Required. A client-specified unique - identifier for the cluster. - - This corresponds to the ``cluster_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.edgecontainer_v1.types.Cluster` A - Google Distributed Cloud Edge Kubernetes cluster. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, cluster, cluster_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, service.CreateClusterRequest): - request = service.CreateClusterRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if cluster is not None: - request.cluster = cluster - if cluster_id is not None: - request.cluster_id = cluster_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_cluster] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - resources.Cluster, - metadata_type=service.OperationMetadata, - ) - - # Done; return the response. - return response - - def update_cluster(self, - request: Optional[Union[service.UpdateClusterRequest, dict]] = None, - *, - cluster: Optional[resources.Cluster] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Updates the parameters of a single Cluster. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import edgecontainer_v1 - - def sample_update_cluster(): - # Create a client - client = edgecontainer_v1.EdgeContainerClient() - - # Initialize request argument(s) - request = edgecontainer_v1.UpdateClusterRequest( - ) - - # Make the request - operation = client.update_cluster(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.edgecontainer_v1.types.UpdateClusterRequest, dict]): - The request object. Updates a cluster. - cluster (google.cloud.edgecontainer_v1.types.Cluster): - The updated cluster. - This corresponds to the ``cluster`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Field mask is used to specify the fields to be - overwritten in the Cluster resource by the update. The - fields specified in the update_mask are relative to the - resource, not the full request. A field will be - overwritten if it is in the mask. If the user does not - provide a mask then all fields will be overwritten. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.edgecontainer_v1.types.Cluster` A - Google Distributed Cloud Edge Kubernetes cluster. - - """ - # Create or coerce a 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([cluster, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, service.UpdateClusterRequest): - request = service.UpdateClusterRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if cluster is not None: - request.cluster = cluster - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_cluster] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("cluster.name", request.cluster.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.Cluster, - metadata_type=service.OperationMetadata, - ) - - # Done; return the response. - return response - - def upgrade_cluster(self, - request: Optional[Union[service.UpgradeClusterRequest, dict]] = None, - *, - name: Optional[str] = None, - target_version: Optional[str] = None, - schedule: Optional[service.UpgradeClusterRequest.Schedule] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Upgrades a single cluster. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import edgecontainer_v1 - - def sample_upgrade_cluster(): - # Create a client - client = edgecontainer_v1.EdgeContainerClient() - - # Initialize request argument(s) - request = edgecontainer_v1.UpgradeClusterRequest( - name="name_value", - target_version="target_version_value", - ) - - # Make the request - operation = client.upgrade_cluster(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.edgecontainer_v1.types.UpgradeClusterRequest, dict]): - The request object. Upgrades a cluster. - name (str): - Required. The resource name of the - cluster. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - target_version (str): - Required. The version the cluster is - going to be upgraded to. - - This corresponds to the ``target_version`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - schedule (google.cloud.edgecontainer_v1.types.UpgradeClusterRequest.Schedule): - The schedule for the upgrade. - This corresponds to the ``schedule`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.edgecontainer_v1.types.Cluster` A - Google Distributed Cloud Edge Kubernetes cluster. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, target_version, schedule]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, service.UpgradeClusterRequest): - request = service.UpgradeClusterRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if target_version is not None: - request.target_version = target_version - if schedule is not None: - request.schedule = schedule - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.upgrade_cluster] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - resources.Cluster, - metadata_type=service.OperationMetadata, - ) - - # Done; return the response. - return response - - def delete_cluster(self, - request: Optional[Union[service.DeleteClusterRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Deletes a single Cluster. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import edgecontainer_v1 - - def sample_delete_cluster(): - # Create a client - client = edgecontainer_v1.EdgeContainerClient() - - # Initialize request argument(s) - request = edgecontainer_v1.DeleteClusterRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_cluster(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.edgecontainer_v1.types.DeleteClusterRequest, dict]): - The request object. Deletes a cluster. - name (str): - Required. The resource name of the - cluster. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.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([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, service.DeleteClusterRequest): - request = service.DeleteClusterRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_cluster] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - empty_pb2.Empty, - metadata_type=service.OperationMetadata, - ) - - # Done; return the response. - return response - - def generate_access_token(self, - request: Optional[Union[service.GenerateAccessTokenRequest, dict]] = None, - *, - cluster: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> service.GenerateAccessTokenResponse: - r"""Generates an access token for a Cluster. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import edgecontainer_v1 - - def sample_generate_access_token(): - # Create a client - client = edgecontainer_v1.EdgeContainerClient() - - # Initialize request argument(s) - request = edgecontainer_v1.GenerateAccessTokenRequest( - cluster="cluster_value", - ) - - # Make the request - response = client.generate_access_token(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.edgecontainer_v1.types.GenerateAccessTokenRequest, dict]): - The request object. Generates an access token for a - cluster. - cluster (str): - Required. The resource name of the - cluster. - - This corresponds to the ``cluster`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.edgecontainer_v1.types.GenerateAccessTokenResponse: - An access token for a cluster. - """ - # Create or coerce a 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([cluster]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, service.GenerateAccessTokenRequest): - request = service.GenerateAccessTokenRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if cluster is not None: - request.cluster = cluster - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.generate_access_token] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("cluster", request.cluster), - )), - ) - - # 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 generate_offline_credential(self, - request: Optional[Union[service.GenerateOfflineCredentialRequest, dict]] = None, - *, - cluster: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> service.GenerateOfflineCredentialResponse: - r"""Generates an offline credential for a Cluster. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import edgecontainer_v1 - - def sample_generate_offline_credential(): - # Create a client - client = edgecontainer_v1.EdgeContainerClient() - - # Initialize request argument(s) - request = edgecontainer_v1.GenerateOfflineCredentialRequest( - cluster="cluster_value", - ) - - # Make the request - response = client.generate_offline_credential(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.edgecontainer_v1.types.GenerateOfflineCredentialRequest, dict]): - The request object. Generates an offline - credential(offline) for a cluster. - cluster (str): - Required. The resource name of the - cluster. - - This corresponds to the ``cluster`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.edgecontainer_v1.types.GenerateOfflineCredentialResponse: - An offline credential for a cluster. - """ - # Create or coerce a 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([cluster]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, service.GenerateOfflineCredentialRequest): - request = service.GenerateOfflineCredentialRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if cluster is not None: - request.cluster = cluster - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.generate_offline_credential] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("cluster", request.cluster), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_node_pools(self, - request: Optional[Union[service.ListNodePoolsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListNodePoolsPager: - r"""Lists NodePools in a given project and location. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import edgecontainer_v1 - - def sample_list_node_pools(): - # Create a client - client = edgecontainer_v1.EdgeContainerClient() - - # Initialize request argument(s) - request = edgecontainer_v1.ListNodePoolsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_node_pools(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.edgecontainer_v1.types.ListNodePoolsRequest, dict]): - The request object. Lists node pools in a cluster. - parent (str): - Required. The parent cluster, which - owns this collection of node pools. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.edgecontainer_v1.services.edge_container.pagers.ListNodePoolsPager: - List of node pools in a cluster. - - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, service.ListNodePoolsRequest): - request = service.ListNodePoolsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_node_pools] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListNodePoolsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_node_pool(self, - request: Optional[Union[service.GetNodePoolRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.NodePool: - r"""Gets details of a single NodePool. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import edgecontainer_v1 - - def sample_get_node_pool(): - # Create a client - client = edgecontainer_v1.EdgeContainerClient() - - # Initialize request argument(s) - request = edgecontainer_v1.GetNodePoolRequest( - name="name_value", - ) - - # Make the request - response = client.get_node_pool(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.edgecontainer_v1.types.GetNodePoolRequest, dict]): - The request object. Gets a node pool. - name (str): - Required. The resource name of the - node pool. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.edgecontainer_v1.types.NodePool: - A set of Kubernetes nodes in a - cluster with common configuration and - specification. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, service.GetNodePoolRequest): - request = service.GetNodePoolRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_node_pool] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def create_node_pool(self, - request: Optional[Union[service.CreateNodePoolRequest, dict]] = None, - *, - parent: Optional[str] = None, - node_pool: Optional[resources.NodePool] = None, - node_pool_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Creates a new NodePool in a given project and - location. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import edgecontainer_v1 - - def sample_create_node_pool(): - # Create a client - client = edgecontainer_v1.EdgeContainerClient() - - # Initialize request argument(s) - node_pool = edgecontainer_v1.NodePool() - node_pool.name = "name_value" - node_pool.node_count = 1070 - - request = edgecontainer_v1.CreateNodePoolRequest( - parent="parent_value", - node_pool_id="node_pool_id_value", - node_pool=node_pool, - ) - - # Make the request - operation = client.create_node_pool(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.edgecontainer_v1.types.CreateNodePoolRequest, dict]): - The request object. Creates a node pool. - parent (str): - Required. The parent cluster where - this node pool will be created. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - node_pool (google.cloud.edgecontainer_v1.types.NodePool): - Required. The node pool to create. - This corresponds to the ``node_pool`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - node_pool_id (str): - Required. A client-specified unique - identifier for the node pool. - - This corresponds to the ``node_pool_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.edgecontainer_v1.types.NodePool` A set of Kubernetes nodes in a cluster with common configuration and - specification. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, node_pool, node_pool_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, service.CreateNodePoolRequest): - request = service.CreateNodePoolRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if node_pool is not None: - request.node_pool = node_pool - if node_pool_id is not None: - request.node_pool_id = node_pool_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_node_pool] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - resources.NodePool, - metadata_type=service.OperationMetadata, - ) - - # Done; return the response. - return response - - def update_node_pool(self, - request: Optional[Union[service.UpdateNodePoolRequest, dict]] = None, - *, - node_pool: Optional[resources.NodePool] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Updates the parameters of a single NodePool. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import edgecontainer_v1 - - def sample_update_node_pool(): - # Create a client - client = edgecontainer_v1.EdgeContainerClient() - - # Initialize request argument(s) - request = edgecontainer_v1.UpdateNodePoolRequest( - ) - - # Make the request - operation = client.update_node_pool(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.edgecontainer_v1.types.UpdateNodePoolRequest, dict]): - The request object. Updates a node pool. - node_pool (google.cloud.edgecontainer_v1.types.NodePool): - The updated node pool. - This corresponds to the ``node_pool`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Field mask is used to specify the fields to be - overwritten in the NodePool resource by the update. The - fields specified in the update_mask are relative to the - resource, not the full request. A field will be - overwritten if it is in the mask. If the user does not - provide a mask then all fields will be overwritten. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.edgecontainer_v1.types.NodePool` A set of Kubernetes nodes in a cluster with common configuration and - specification. - - """ - # Create or coerce a 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([node_pool, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, service.UpdateNodePoolRequest): - request = service.UpdateNodePoolRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if node_pool is not None: - request.node_pool = node_pool - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_node_pool] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("node_pool.name", request.node_pool.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.NodePool, - metadata_type=service.OperationMetadata, - ) - - # Done; return the response. - return response - - def delete_node_pool(self, - request: Optional[Union[service.DeleteNodePoolRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Deletes a single NodePool. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import edgecontainer_v1 - - def sample_delete_node_pool(): - # Create a client - client = edgecontainer_v1.EdgeContainerClient() - - # Initialize request argument(s) - request = edgecontainer_v1.DeleteNodePoolRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_node_pool(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.edgecontainer_v1.types.DeleteNodePoolRequest, dict]): - The request object. Deletes a node pool. - name (str): - Required. The resource name of the - node pool. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.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([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, service.DeleteNodePoolRequest): - request = service.DeleteNodePoolRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_node_pool] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - empty_pb2.Empty, - metadata_type=service.OperationMetadata, - ) - - # Done; return the response. - return response - - def list_machines(self, - request: Optional[Union[service.ListMachinesRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListMachinesPager: - r"""Lists Machines in a given project and location. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import edgecontainer_v1 - - def sample_list_machines(): - # Create a client - client = edgecontainer_v1.EdgeContainerClient() - - # Initialize request argument(s) - request = edgecontainer_v1.ListMachinesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_machines(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.edgecontainer_v1.types.ListMachinesRequest, dict]): - The request object. Lists machines in a site. - parent (str): - Required. The parent site, which owns - this collection of machines. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.edgecontainer_v1.services.edge_container.pagers.ListMachinesPager: - List of machines in a site. - - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, service.ListMachinesRequest): - request = service.ListMachinesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_machines] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListMachinesPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_machine(self, - request: Optional[Union[service.GetMachineRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.Machine: - r"""Gets details of a single Machine. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import edgecontainer_v1 - - def sample_get_machine(): - # Create a client - client = edgecontainer_v1.EdgeContainerClient() - - # Initialize request argument(s) - request = edgecontainer_v1.GetMachineRequest( - name="name_value", - ) - - # Make the request - response = client.get_machine(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.edgecontainer_v1.types.GetMachineRequest, dict]): - The request object. Gets a machine. - name (str): - Required. The resource name of the - machine. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.edgecontainer_v1.types.Machine: - A Google Distributed Cloud Edge - machine capable of acting as a - Kubernetes node. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, service.GetMachineRequest): - request = service.GetMachineRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_machine] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_vpn_connections(self, - request: Optional[Union[service.ListVpnConnectionsRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListVpnConnectionsPager: - r"""Lists VPN connections in a given project and - location. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import edgecontainer_v1 - - def sample_list_vpn_connections(): - # Create a client - client = edgecontainer_v1.EdgeContainerClient() - - # Initialize request argument(s) - request = edgecontainer_v1.ListVpnConnectionsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_vpn_connections(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.edgecontainer_v1.types.ListVpnConnectionsRequest, dict]): - The request object. Lists VPN connections. - parent (str): - Required. The parent location, which - owns this collection of VPN connections. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.edgecontainer_v1.services.edge_container.pagers.ListVpnConnectionsPager: - List of VPN connections in a - location. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, service.ListVpnConnectionsRequest): - request = service.ListVpnConnectionsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_vpn_connections] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListVpnConnectionsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_vpn_connection(self, - request: Optional[Union[service.GetVpnConnectionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.VpnConnection: - r"""Gets details of a single VPN connection. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import edgecontainer_v1 - - def sample_get_vpn_connection(): - # Create a client - client = edgecontainer_v1.EdgeContainerClient() - - # Initialize request argument(s) - request = edgecontainer_v1.GetVpnConnectionRequest( - name="name_value", - ) - - # Make the request - response = client.get_vpn_connection(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.edgecontainer_v1.types.GetVpnConnectionRequest, dict]): - The request object. Gets a VPN connection. - name (str): - Required. The resource name of the - vpn connection. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.edgecontainer_v1.types.VpnConnection: - A VPN connection . - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, service.GetVpnConnectionRequest): - request = service.GetVpnConnectionRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_vpn_connection] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def create_vpn_connection(self, - request: Optional[Union[service.CreateVpnConnectionRequest, dict]] = None, - *, - parent: Optional[str] = None, - vpn_connection: Optional[resources.VpnConnection] = None, - vpn_connection_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Creates a new VPN connection in a given project and - location. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import edgecontainer_v1 - - def sample_create_vpn_connection(): - # Create a client - client = edgecontainer_v1.EdgeContainerClient() - - # Initialize request argument(s) - vpn_connection = edgecontainer_v1.VpnConnection() - vpn_connection.name = "name_value" - - request = edgecontainer_v1.CreateVpnConnectionRequest( - parent="parent_value", - vpn_connection_id="vpn_connection_id_value", - vpn_connection=vpn_connection, - ) - - # Make the request - operation = client.create_vpn_connection(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.edgecontainer_v1.types.CreateVpnConnectionRequest, dict]): - The request object. Creates a VPN connection. - parent (str): - Required. The parent location where - this vpn connection will be created. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - vpn_connection (google.cloud.edgecontainer_v1.types.VpnConnection): - Required. The VPN connection to - create. - - This corresponds to the ``vpn_connection`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - vpn_connection_id (str): - Required. The VPN connection - identifier. - - This corresponds to the ``vpn_connection_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:`google.cloud.edgecontainer_v1.types.VpnConnection` - A VPN connection . - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, vpn_connection, vpn_connection_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, service.CreateVpnConnectionRequest): - request = service.CreateVpnConnectionRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if vpn_connection is not None: - request.vpn_connection = vpn_connection - if vpn_connection_id is not None: - request.vpn_connection_id = vpn_connection_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_vpn_connection] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - resources.VpnConnection, - metadata_type=service.OperationMetadata, - ) - - # Done; return the response. - return response - - def delete_vpn_connection(self, - request: Optional[Union[service.DeleteVpnConnectionRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Deletes a single VPN connection. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import edgecontainer_v1 - - def sample_delete_vpn_connection(): - # Create a client - client = edgecontainer_v1.EdgeContainerClient() - - # Initialize request argument(s) - request = edgecontainer_v1.DeleteVpnConnectionRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_vpn_connection(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.edgecontainer_v1.types.DeleteVpnConnectionRequest, dict]): - The request object. Deletes a vpn connection. - name (str): - Required. The resource name of the - vpn connection. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.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([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, service.DeleteVpnConnectionRequest): - request = service.DeleteVpnConnectionRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_vpn_connection] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - empty_pb2.Empty, - metadata_type=service.OperationMetadata, - ) - - # Done; return the response. - return response - - def get_server_config(self, - request: Optional[Union[service.GetServerConfigRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.ServerConfig: - r"""Gets the server config. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import edgecontainer_v1 - - def sample_get_server_config(): - # Create a client - client = edgecontainer_v1.EdgeContainerClient() - - # Initialize request argument(s) - request = edgecontainer_v1.GetServerConfigRequest( - name="name_value", - ) - - # Make the request - response = client.get_server_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.edgecontainer_v1.types.GetServerConfigRequest, dict]): - The request object. Gets the server config. - name (str): - Required. The name (project and location) of the server - config to get, specified in the format - ``projects/*/locations/*``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.edgecontainer_v1.types.ServerConfig: - Server configuration for supported - versions and release channels. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, service.GetServerConfigRequest): - request = service.GetServerConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_server_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "EdgeContainerClient": - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - self.transport.close() - - def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = 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 get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_operation] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def delete_operation( - self, - request: Optional[operations_pb2.DeleteOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a long-running operation. - - This method indicates that the client is no longer interested - in the operation result. It does not cancel the operation. - If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.DeleteOperationRequest`): - The request object. Request message for - `DeleteOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.DeleteOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_operation] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - def cancel_operation( - self, - request: Optional[operations_pb2.CancelOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Starts asynchronous cancellation on a long-running operation. - - The server makes a best effort to cancel the operation, but success - is not guaranteed. If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.CancelOperationRequest`): - The request object. Request message for - `CancelOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.CancelOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.cancel_operation] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - def get_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.GetLocationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_location] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def list_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.ListLocationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_locations] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # 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__ = ( - "EdgeContainerClient", -) diff --git a/owl-bot-staging/google-cloud-edgecontainer/v1/google/cloud/edgecontainer_v1/services/edge_container/pagers.py b/owl-bot-staging/google-cloud-edgecontainer/v1/google/cloud/edgecontainer_v1/services/edge_container/pagers.py deleted file mode 100644 index 4d3f6a82bd13..000000000000 --- a/owl-bot-staging/google-cloud-edgecontainer/v1/google/cloud/edgecontainer_v1/services/edge_container/pagers.py +++ /dev/null @@ -1,568 +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.cloud.edgecontainer_v1.types import resources -from google.cloud.edgecontainer_v1.types import service - - -class ListClustersPager: - """A pager for iterating through ``list_clusters`` requests. - - This class thinly wraps an initial - :class:`google.cloud.edgecontainer_v1.types.ListClustersResponse` object, and - provides an ``__iter__`` method to iterate through its - ``clusters`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListClusters`` requests and continue to iterate - through the ``clusters`` field on the - corresponding responses. - - All the usual :class:`google.cloud.edgecontainer_v1.types.ListClustersResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., service.ListClustersResponse], - request: service.ListClustersRequest, - response: service.ListClustersResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.edgecontainer_v1.types.ListClustersRequest): - The initial request object. - response (google.cloud.edgecontainer_v1.types.ListClustersResponse): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = service.ListClustersRequest(request) - self._response = response - self._retry = retry - self._timeout = timeout - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[service.ListClustersResponse]: - 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.Cluster]: - for page in self.pages: - yield from page.clusters - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListClustersAsyncPager: - """A pager for iterating through ``list_clusters`` requests. - - This class thinly wraps an initial - :class:`google.cloud.edgecontainer_v1.types.ListClustersResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``clusters`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListClusters`` requests and continue to iterate - through the ``clusters`` field on the - corresponding responses. - - All the usual :class:`google.cloud.edgecontainer_v1.types.ListClustersResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., Awaitable[service.ListClustersResponse]], - request: service.ListClustersRequest, - response: service.ListClustersResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.edgecontainer_v1.types.ListClustersRequest): - The initial request object. - response (google.cloud.edgecontainer_v1.types.ListClustersResponse): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = service.ListClustersRequest(request) - self._response = response - self._retry = retry - self._timeout = timeout - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[service.ListClustersResponse]: - 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.Cluster]: - async def async_generator(): - async for page in self.pages: - for response in page.clusters: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListNodePoolsPager: - """A pager for iterating through ``list_node_pools`` requests. - - This class thinly wraps an initial - :class:`google.cloud.edgecontainer_v1.types.ListNodePoolsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``node_pools`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListNodePools`` requests and continue to iterate - through the ``node_pools`` field on the - corresponding responses. - - All the usual :class:`google.cloud.edgecontainer_v1.types.ListNodePoolsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., service.ListNodePoolsResponse], - request: service.ListNodePoolsRequest, - response: service.ListNodePoolsResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.edgecontainer_v1.types.ListNodePoolsRequest): - The initial request object. - response (google.cloud.edgecontainer_v1.types.ListNodePoolsResponse): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = service.ListNodePoolsRequest(request) - self._response = response - self._retry = retry - self._timeout = timeout - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[service.ListNodePoolsResponse]: - 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.NodePool]: - for page in self.pages: - yield from page.node_pools - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListNodePoolsAsyncPager: - """A pager for iterating through ``list_node_pools`` requests. - - This class thinly wraps an initial - :class:`google.cloud.edgecontainer_v1.types.ListNodePoolsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``node_pools`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListNodePools`` requests and continue to iterate - through the ``node_pools`` field on the - corresponding responses. - - All the usual :class:`google.cloud.edgecontainer_v1.types.ListNodePoolsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., Awaitable[service.ListNodePoolsResponse]], - request: service.ListNodePoolsRequest, - response: service.ListNodePoolsResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.edgecontainer_v1.types.ListNodePoolsRequest): - The initial request object. - response (google.cloud.edgecontainer_v1.types.ListNodePoolsResponse): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = service.ListNodePoolsRequest(request) - self._response = response - self._retry = retry - self._timeout = timeout - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[service.ListNodePoolsResponse]: - 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.NodePool]: - async def async_generator(): - async for page in self.pages: - for response in page.node_pools: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListMachinesPager: - """A pager for iterating through ``list_machines`` requests. - - This class thinly wraps an initial - :class:`google.cloud.edgecontainer_v1.types.ListMachinesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``machines`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListMachines`` requests and continue to iterate - through the ``machines`` field on the - corresponding responses. - - All the usual :class:`google.cloud.edgecontainer_v1.types.ListMachinesResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., service.ListMachinesResponse], - request: service.ListMachinesRequest, - response: service.ListMachinesResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.edgecontainer_v1.types.ListMachinesRequest): - The initial request object. - response (google.cloud.edgecontainer_v1.types.ListMachinesResponse): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = service.ListMachinesRequest(request) - self._response = response - self._retry = retry - self._timeout = timeout - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[service.ListMachinesResponse]: - 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.Machine]: - for page in self.pages: - yield from page.machines - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListMachinesAsyncPager: - """A pager for iterating through ``list_machines`` requests. - - This class thinly wraps an initial - :class:`google.cloud.edgecontainer_v1.types.ListMachinesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``machines`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListMachines`` requests and continue to iterate - through the ``machines`` field on the - corresponding responses. - - All the usual :class:`google.cloud.edgecontainer_v1.types.ListMachinesResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., Awaitable[service.ListMachinesResponse]], - request: service.ListMachinesRequest, - response: service.ListMachinesResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.edgecontainer_v1.types.ListMachinesRequest): - The initial request object. - response (google.cloud.edgecontainer_v1.types.ListMachinesResponse): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = service.ListMachinesRequest(request) - self._response = response - self._retry = retry - self._timeout = timeout - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[service.ListMachinesResponse]: - 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.Machine]: - async def async_generator(): - async for page in self.pages: - for response in page.machines: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListVpnConnectionsPager: - """A pager for iterating through ``list_vpn_connections`` requests. - - This class thinly wraps an initial - :class:`google.cloud.edgecontainer_v1.types.ListVpnConnectionsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``vpn_connections`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListVpnConnections`` requests and continue to iterate - through the ``vpn_connections`` field on the - corresponding responses. - - All the usual :class:`google.cloud.edgecontainer_v1.types.ListVpnConnectionsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., service.ListVpnConnectionsResponse], - request: service.ListVpnConnectionsRequest, - response: service.ListVpnConnectionsResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.edgecontainer_v1.types.ListVpnConnectionsRequest): - The initial request object. - response (google.cloud.edgecontainer_v1.types.ListVpnConnectionsResponse): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = service.ListVpnConnectionsRequest(request) - self._response = response - self._retry = retry - self._timeout = timeout - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[service.ListVpnConnectionsResponse]: - 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.VpnConnection]: - for page in self.pages: - yield from page.vpn_connections - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListVpnConnectionsAsyncPager: - """A pager for iterating through ``list_vpn_connections`` requests. - - This class thinly wraps an initial - :class:`google.cloud.edgecontainer_v1.types.ListVpnConnectionsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``vpn_connections`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListVpnConnections`` requests and continue to iterate - through the ``vpn_connections`` field on the - corresponding responses. - - All the usual :class:`google.cloud.edgecontainer_v1.types.ListVpnConnectionsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., Awaitable[service.ListVpnConnectionsResponse]], - request: service.ListVpnConnectionsRequest, - response: service.ListVpnConnectionsResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = ()): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.cloud.edgecontainer_v1.types.ListVpnConnectionsRequest): - The initial request object. - response (google.cloud.edgecontainer_v1.types.ListVpnConnectionsResponse): - 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, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = service.ListVpnConnectionsRequest(request) - self._response = response - self._retry = retry - self._timeout = timeout - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[service.ListVpnConnectionsResponse]: - 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.VpnConnection]: - async def async_generator(): - async for page in self.pages: - for response in page.vpn_connections: - 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-edgecontainer/v1/google/cloud/edgecontainer_v1/services/edge_container/transports/README.rst b/owl-bot-staging/google-cloud-edgecontainer/v1/google/cloud/edgecontainer_v1/services/edge_container/transports/README.rst deleted file mode 100644 index aee887ff00b3..000000000000 --- a/owl-bot-staging/google-cloud-edgecontainer/v1/google/cloud/edgecontainer_v1/services/edge_container/transports/README.rst +++ /dev/null @@ -1,9 +0,0 @@ - -transport inheritance structure -_______________________________ - -`EdgeContainerTransport` is the ABC for all transports. -- public child `EdgeContainerGrpcTransport` for sync gRPC transport (defined in `grpc.py`). -- public child `EdgeContainerGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). -- private child `_BaseEdgeContainerRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). -- public child `EdgeContainerRestTransport` 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-edgecontainer/v1/google/cloud/edgecontainer_v1/services/edge_container/transports/__init__.py b/owl-bot-staging/google-cloud-edgecontainer/v1/google/cloud/edgecontainer_v1/services/edge_container/transports/__init__.py deleted file mode 100644 index 7412dbeb737b..000000000000 --- a/owl-bot-staging/google-cloud-edgecontainer/v1/google/cloud/edgecontainer_v1/services/edge_container/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 EdgeContainerTransport -from .grpc import EdgeContainerGrpcTransport -from .grpc_asyncio import EdgeContainerGrpcAsyncIOTransport -from .rest import EdgeContainerRestTransport -from .rest import EdgeContainerRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[EdgeContainerTransport]] -_transport_registry['grpc'] = EdgeContainerGrpcTransport -_transport_registry['grpc_asyncio'] = EdgeContainerGrpcAsyncIOTransport -_transport_registry['rest'] = EdgeContainerRestTransport - -__all__ = ( - 'EdgeContainerTransport', - 'EdgeContainerGrpcTransport', - 'EdgeContainerGrpcAsyncIOTransport', - 'EdgeContainerRestTransport', - 'EdgeContainerRestInterceptor', -) diff --git a/owl-bot-staging/google-cloud-edgecontainer/v1/google/cloud/edgecontainer_v1/services/edge_container/transports/base.py b/owl-bot-staging/google-cloud-edgecontainer/v1/google/cloud/edgecontainer_v1/services/edge_container/transports/base.py deleted file mode 100644 index 4f5b37ee39ad..000000000000 --- a/owl-bot-staging/google-cloud-edgecontainer/v1/google/cloud/edgecontainer_v1/services/edge_container/transports/base.py +++ /dev/null @@ -1,610 +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.edgecontainer_v1 import gapic_version as package_version - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.edgecontainer_v1.types import resources -from google.cloud.edgecontainer_v1.types import service -from google.cloud.location import locations_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 EdgeContainerTransport(abc.ABC): - """Abstract transport class for EdgeContainer.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'edgecontainer.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: 'edgecontainer.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_clusters: gapic_v1.method.wrap_method( - self.list_clusters, - default_retry=retries.Retry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_cluster: gapic_v1.method.wrap_method( - self.get_cluster, - default_retry=retries.Retry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.create_cluster: gapic_v1.method.wrap_method( - self.create_cluster, - default_timeout=60.0, - client_info=client_info, - ), - self.update_cluster: gapic_v1.method.wrap_method( - self.update_cluster, - default_timeout=60.0, - client_info=client_info, - ), - self.upgrade_cluster: gapic_v1.method.wrap_method( - self.upgrade_cluster, - default_timeout=60.0, - client_info=client_info, - ), - self.delete_cluster: gapic_v1.method.wrap_method( - self.delete_cluster, - default_timeout=60.0, - client_info=client_info, - ), - self.generate_access_token: gapic_v1.method.wrap_method( - self.generate_access_token, - default_retry=retries.Retry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.generate_offline_credential: gapic_v1.method.wrap_method( - self.generate_offline_credential, - default_retry=retries.Retry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_node_pools: gapic_v1.method.wrap_method( - self.list_node_pools, - default_retry=retries.Retry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_node_pool: gapic_v1.method.wrap_method( - self.get_node_pool, - default_retry=retries.Retry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.create_node_pool: gapic_v1.method.wrap_method( - self.create_node_pool, - default_timeout=60.0, - client_info=client_info, - ), - self.update_node_pool: gapic_v1.method.wrap_method( - self.update_node_pool, - default_timeout=60.0, - client_info=client_info, - ), - self.delete_node_pool: gapic_v1.method.wrap_method( - self.delete_node_pool, - default_timeout=60.0, - client_info=client_info, - ), - self.list_machines: gapic_v1.method.wrap_method( - self.list_machines, - default_retry=retries.Retry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_machine: gapic_v1.method.wrap_method( - self.get_machine, - default_retry=retries.Retry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_vpn_connections: gapic_v1.method.wrap_method( - self.list_vpn_connections, - default_retry=retries.Retry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_vpn_connection: gapic_v1.method.wrap_method( - self.get_vpn_connection, - default_retry=retries.Retry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.create_vpn_connection: gapic_v1.method.wrap_method( - self.create_vpn_connection, - default_timeout=60.0, - client_info=client_info, - ), - self.delete_vpn_connection: gapic_v1.method.wrap_method( - self.delete_vpn_connection, - default_timeout=60.0, - client_info=client_info, - ), - self.get_server_config: gapic_v1.method.wrap_method( - self.get_server_config, - default_retry=retries.Retry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_location: gapic_v1.method.wrap_method( - self.get_location, - default_timeout=None, - client_info=client_info, - ), - self.list_locations: gapic_v1.method.wrap_method( - self.list_locations, - default_timeout=None, - client_info=client_info, - ), - self.cancel_operation: gapic_v1.method.wrap_method( - self.cancel_operation, - default_timeout=None, - client_info=client_info, - ), - self.delete_operation: gapic_v1.method.wrap_method( - self.delete_operation, - default_timeout=None, - client_info=client_info, - ), - self.get_operation: gapic_v1.method.wrap_method( - self.get_operation, - default_timeout=None, - client_info=client_info, - ), - self.list_operations: gapic_v1.method.wrap_method( - self.list_operations, - default_timeout=None, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def operations_client(self): - """Return the client designed to process long-running operations.""" - raise NotImplementedError() - - @property - def list_clusters(self) -> Callable[ - [service.ListClustersRequest], - Union[ - service.ListClustersResponse, - Awaitable[service.ListClustersResponse] - ]]: - raise NotImplementedError() - - @property - def get_cluster(self) -> Callable[ - [service.GetClusterRequest], - Union[ - resources.Cluster, - Awaitable[resources.Cluster] - ]]: - raise NotImplementedError() - - @property - def create_cluster(self) -> Callable[ - [service.CreateClusterRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def update_cluster(self) -> Callable[ - [service.UpdateClusterRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def upgrade_cluster(self) -> Callable[ - [service.UpgradeClusterRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def delete_cluster(self) -> Callable[ - [service.DeleteClusterRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def generate_access_token(self) -> Callable[ - [service.GenerateAccessTokenRequest], - Union[ - service.GenerateAccessTokenResponse, - Awaitable[service.GenerateAccessTokenResponse] - ]]: - raise NotImplementedError() - - @property - def generate_offline_credential(self) -> Callable[ - [service.GenerateOfflineCredentialRequest], - Union[ - service.GenerateOfflineCredentialResponse, - Awaitable[service.GenerateOfflineCredentialResponse] - ]]: - raise NotImplementedError() - - @property - def list_node_pools(self) -> Callable[ - [service.ListNodePoolsRequest], - Union[ - service.ListNodePoolsResponse, - Awaitable[service.ListNodePoolsResponse] - ]]: - raise NotImplementedError() - - @property - def get_node_pool(self) -> Callable[ - [service.GetNodePoolRequest], - Union[ - resources.NodePool, - Awaitable[resources.NodePool] - ]]: - raise NotImplementedError() - - @property - def create_node_pool(self) -> Callable[ - [service.CreateNodePoolRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def update_node_pool(self) -> Callable[ - [service.UpdateNodePoolRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def delete_node_pool(self) -> Callable[ - [service.DeleteNodePoolRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def list_machines(self) -> Callable[ - [service.ListMachinesRequest], - Union[ - service.ListMachinesResponse, - Awaitable[service.ListMachinesResponse] - ]]: - raise NotImplementedError() - - @property - def get_machine(self) -> Callable[ - [service.GetMachineRequest], - Union[ - resources.Machine, - Awaitable[resources.Machine] - ]]: - raise NotImplementedError() - - @property - def list_vpn_connections(self) -> Callable[ - [service.ListVpnConnectionsRequest], - Union[ - service.ListVpnConnectionsResponse, - Awaitable[service.ListVpnConnectionsResponse] - ]]: - raise NotImplementedError() - - @property - def get_vpn_connection(self) -> Callable[ - [service.GetVpnConnectionRequest], - Union[ - resources.VpnConnection, - Awaitable[resources.VpnConnection] - ]]: - raise NotImplementedError() - - @property - def create_vpn_connection(self) -> Callable[ - [service.CreateVpnConnectionRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def delete_vpn_connection(self) -> Callable[ - [service.DeleteVpnConnectionRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def get_server_config(self) -> Callable[ - [service.GetServerConfigRequest], - Union[ - resources.ServerConfig, - Awaitable[resources.ServerConfig] - ]]: - raise NotImplementedError() - - @property - def list_operations( - self, - ) -> Callable[ - [operations_pb2.ListOperationsRequest], - Union[operations_pb2.ListOperationsResponse, Awaitable[operations_pb2.ListOperationsResponse]], - ]: - raise NotImplementedError() - - @property - def get_operation( - self, - ) -> Callable[ - [operations_pb2.GetOperationRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: - raise NotImplementedError() - - @property - def cancel_operation( - self, - ) -> Callable[ - [operations_pb2.CancelOperationRequest], - None, - ]: - raise NotImplementedError() - - @property - def delete_operation( - self, - ) -> Callable[ - [operations_pb2.DeleteOperationRequest], - None, - ]: - raise NotImplementedError() - - @property - def get_location(self, - ) -> Callable[ - [locations_pb2.GetLocationRequest], - Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], - ]: - raise NotImplementedError() - - @property - def list_locations(self, - ) -> Callable[ - [locations_pb2.ListLocationsRequest], - Union[locations_pb2.ListLocationsResponse, Awaitable[locations_pb2.ListLocationsResponse]], - ]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'EdgeContainerTransport', -) diff --git a/owl-bot-staging/google-cloud-edgecontainer/v1/google/cloud/edgecontainer_v1/services/edge_container/transports/grpc.py b/owl-bot-staging/google-cloud-edgecontainer/v1/google/cloud/edgecontainer_v1/services/edge_container/transports/grpc.py deleted file mode 100644 index 3476e56e0c89..000000000000 --- a/owl-bot-staging/google-cloud-edgecontainer/v1/google/cloud/edgecontainer_v1/services/edge_container/transports/grpc.py +++ /dev/null @@ -1,898 +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 warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import operations_v1 -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.edgecontainer_v1.types import resources -from google.cloud.edgecontainer_v1.types import service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from .base import EdgeContainerTransport, DEFAULT_CLIENT_INFO - - -class EdgeContainerGrpcTransport(EdgeContainerTransport): - """gRPC backend transport for EdgeContainer. - - EdgeContainer API provides management of Kubernetes Clusters - on Google Edge Cloud deployments. - - 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 = 'edgecontainer.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: 'edgecontainer.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), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'edgecontainer.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def list_clusters(self) -> Callable[ - [service.ListClustersRequest], - service.ListClustersResponse]: - r"""Return a callable for the list clusters method over gRPC. - - Lists Clusters in a given project and location. - - Returns: - Callable[[~.ListClustersRequest], - ~.ListClustersResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_clusters' not in self._stubs: - self._stubs['list_clusters'] = self.grpc_channel.unary_unary( - '/google.cloud.edgecontainer.v1.EdgeContainer/ListClusters', - request_serializer=service.ListClustersRequest.serialize, - response_deserializer=service.ListClustersResponse.deserialize, - ) - return self._stubs['list_clusters'] - - @property - def get_cluster(self) -> Callable[ - [service.GetClusterRequest], - resources.Cluster]: - r"""Return a callable for the get cluster method over gRPC. - - Gets details of a single Cluster. - - Returns: - Callable[[~.GetClusterRequest], - ~.Cluster]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_cluster' not in self._stubs: - self._stubs['get_cluster'] = self.grpc_channel.unary_unary( - '/google.cloud.edgecontainer.v1.EdgeContainer/GetCluster', - request_serializer=service.GetClusterRequest.serialize, - response_deserializer=resources.Cluster.deserialize, - ) - return self._stubs['get_cluster'] - - @property - def create_cluster(self) -> Callable[ - [service.CreateClusterRequest], - operations_pb2.Operation]: - r"""Return a callable for the create cluster method over gRPC. - - Creates a new Cluster in a given project and - location. - - Returns: - Callable[[~.CreateClusterRequest], - ~.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_cluster' not in self._stubs: - self._stubs['create_cluster'] = self.grpc_channel.unary_unary( - '/google.cloud.edgecontainer.v1.EdgeContainer/CreateCluster', - request_serializer=service.CreateClusterRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_cluster'] - - @property - def update_cluster(self) -> Callable[ - [service.UpdateClusterRequest], - operations_pb2.Operation]: - r"""Return a callable for the update cluster method over gRPC. - - Updates the parameters of a single Cluster. - - Returns: - Callable[[~.UpdateClusterRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'update_cluster' not in self._stubs: - self._stubs['update_cluster'] = self.grpc_channel.unary_unary( - '/google.cloud.edgecontainer.v1.EdgeContainer/UpdateCluster', - request_serializer=service.UpdateClusterRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_cluster'] - - @property - def upgrade_cluster(self) -> Callable[ - [service.UpgradeClusterRequest], - operations_pb2.Operation]: - r"""Return a callable for the upgrade cluster method over gRPC. - - Upgrades a single cluster. - - Returns: - Callable[[~.UpgradeClusterRequest], - ~.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 'upgrade_cluster' not in self._stubs: - self._stubs['upgrade_cluster'] = self.grpc_channel.unary_unary( - '/google.cloud.edgecontainer.v1.EdgeContainer/UpgradeCluster', - request_serializer=service.UpgradeClusterRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['upgrade_cluster'] - - @property - def delete_cluster(self) -> Callable[ - [service.DeleteClusterRequest], - operations_pb2.Operation]: - r"""Return a callable for the delete cluster method over gRPC. - - Deletes a single Cluster. - - Returns: - Callable[[~.DeleteClusterRequest], - ~.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_cluster' not in self._stubs: - self._stubs['delete_cluster'] = self.grpc_channel.unary_unary( - '/google.cloud.edgecontainer.v1.EdgeContainer/DeleteCluster', - request_serializer=service.DeleteClusterRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_cluster'] - - @property - def generate_access_token(self) -> Callable[ - [service.GenerateAccessTokenRequest], - service.GenerateAccessTokenResponse]: - r"""Return a callable for the generate access token method over gRPC. - - Generates an access token for a Cluster. - - Returns: - Callable[[~.GenerateAccessTokenRequest], - ~.GenerateAccessTokenResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_access_token' not in self._stubs: - self._stubs['generate_access_token'] = self.grpc_channel.unary_unary( - '/google.cloud.edgecontainer.v1.EdgeContainer/GenerateAccessToken', - request_serializer=service.GenerateAccessTokenRequest.serialize, - response_deserializer=service.GenerateAccessTokenResponse.deserialize, - ) - return self._stubs['generate_access_token'] - - @property - def generate_offline_credential(self) -> Callable[ - [service.GenerateOfflineCredentialRequest], - service.GenerateOfflineCredentialResponse]: - r"""Return a callable for the generate offline credential method over gRPC. - - Generates an offline credential for a Cluster. - - Returns: - Callable[[~.GenerateOfflineCredentialRequest], - ~.GenerateOfflineCredentialResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_offline_credential' not in self._stubs: - self._stubs['generate_offline_credential'] = self.grpc_channel.unary_unary( - '/google.cloud.edgecontainer.v1.EdgeContainer/GenerateOfflineCredential', - request_serializer=service.GenerateOfflineCredentialRequest.serialize, - response_deserializer=service.GenerateOfflineCredentialResponse.deserialize, - ) - return self._stubs['generate_offline_credential'] - - @property - def list_node_pools(self) -> Callable[ - [service.ListNodePoolsRequest], - service.ListNodePoolsResponse]: - r"""Return a callable for the list node pools method over gRPC. - - Lists NodePools in a given project and location. - - Returns: - Callable[[~.ListNodePoolsRequest], - ~.ListNodePoolsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_node_pools' not in self._stubs: - self._stubs['list_node_pools'] = self.grpc_channel.unary_unary( - '/google.cloud.edgecontainer.v1.EdgeContainer/ListNodePools', - request_serializer=service.ListNodePoolsRequest.serialize, - response_deserializer=service.ListNodePoolsResponse.deserialize, - ) - return self._stubs['list_node_pools'] - - @property - def get_node_pool(self) -> Callable[ - [service.GetNodePoolRequest], - resources.NodePool]: - r"""Return a callable for the get node pool method over gRPC. - - Gets details of a single NodePool. - - Returns: - Callable[[~.GetNodePoolRequest], - ~.NodePool]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_node_pool' not in self._stubs: - self._stubs['get_node_pool'] = self.grpc_channel.unary_unary( - '/google.cloud.edgecontainer.v1.EdgeContainer/GetNodePool', - request_serializer=service.GetNodePoolRequest.serialize, - response_deserializer=resources.NodePool.deserialize, - ) - return self._stubs['get_node_pool'] - - @property - def create_node_pool(self) -> Callable[ - [service.CreateNodePoolRequest], - operations_pb2.Operation]: - r"""Return a callable for the create node pool method over gRPC. - - Creates a new NodePool in a given project and - location. - - Returns: - Callable[[~.CreateNodePoolRequest], - ~.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_node_pool' not in self._stubs: - self._stubs['create_node_pool'] = self.grpc_channel.unary_unary( - '/google.cloud.edgecontainer.v1.EdgeContainer/CreateNodePool', - request_serializer=service.CreateNodePoolRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_node_pool'] - - @property - def update_node_pool(self) -> Callable[ - [service.UpdateNodePoolRequest], - operations_pb2.Operation]: - r"""Return a callable for the update node pool method over gRPC. - - Updates the parameters of a single NodePool. - - Returns: - Callable[[~.UpdateNodePoolRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'update_node_pool' not in self._stubs: - self._stubs['update_node_pool'] = self.grpc_channel.unary_unary( - '/google.cloud.edgecontainer.v1.EdgeContainer/UpdateNodePool', - request_serializer=service.UpdateNodePoolRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_node_pool'] - - @property - def delete_node_pool(self) -> Callable[ - [service.DeleteNodePoolRequest], - operations_pb2.Operation]: - r"""Return a callable for the delete node pool method over gRPC. - - Deletes a single NodePool. - - Returns: - Callable[[~.DeleteNodePoolRequest], - ~.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_node_pool' not in self._stubs: - self._stubs['delete_node_pool'] = self.grpc_channel.unary_unary( - '/google.cloud.edgecontainer.v1.EdgeContainer/DeleteNodePool', - request_serializer=service.DeleteNodePoolRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_node_pool'] - - @property - def list_machines(self) -> Callable[ - [service.ListMachinesRequest], - service.ListMachinesResponse]: - r"""Return a callable for the list machines method over gRPC. - - Lists Machines in a given project and location. - - Returns: - Callable[[~.ListMachinesRequest], - ~.ListMachinesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_machines' not in self._stubs: - self._stubs['list_machines'] = self.grpc_channel.unary_unary( - '/google.cloud.edgecontainer.v1.EdgeContainer/ListMachines', - request_serializer=service.ListMachinesRequest.serialize, - response_deserializer=service.ListMachinesResponse.deserialize, - ) - return self._stubs['list_machines'] - - @property - def get_machine(self) -> Callable[ - [service.GetMachineRequest], - resources.Machine]: - r"""Return a callable for the get machine method over gRPC. - - Gets details of a single Machine. - - Returns: - Callable[[~.GetMachineRequest], - ~.Machine]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_machine' not in self._stubs: - self._stubs['get_machine'] = self.grpc_channel.unary_unary( - '/google.cloud.edgecontainer.v1.EdgeContainer/GetMachine', - request_serializer=service.GetMachineRequest.serialize, - response_deserializer=resources.Machine.deserialize, - ) - return self._stubs['get_machine'] - - @property - def list_vpn_connections(self) -> Callable[ - [service.ListVpnConnectionsRequest], - service.ListVpnConnectionsResponse]: - r"""Return a callable for the list vpn connections method over gRPC. - - Lists VPN connections in a given project and - location. - - Returns: - Callable[[~.ListVpnConnectionsRequest], - ~.ListVpnConnectionsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_vpn_connections' not in self._stubs: - self._stubs['list_vpn_connections'] = self.grpc_channel.unary_unary( - '/google.cloud.edgecontainer.v1.EdgeContainer/ListVpnConnections', - request_serializer=service.ListVpnConnectionsRequest.serialize, - response_deserializer=service.ListVpnConnectionsResponse.deserialize, - ) - return self._stubs['list_vpn_connections'] - - @property - def get_vpn_connection(self) -> Callable[ - [service.GetVpnConnectionRequest], - resources.VpnConnection]: - r"""Return a callable for the get vpn connection method over gRPC. - - Gets details of a single VPN connection. - - Returns: - Callable[[~.GetVpnConnectionRequest], - ~.VpnConnection]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_vpn_connection' not in self._stubs: - self._stubs['get_vpn_connection'] = self.grpc_channel.unary_unary( - '/google.cloud.edgecontainer.v1.EdgeContainer/GetVpnConnection', - request_serializer=service.GetVpnConnectionRequest.serialize, - response_deserializer=resources.VpnConnection.deserialize, - ) - return self._stubs['get_vpn_connection'] - - @property - def create_vpn_connection(self) -> Callable[ - [service.CreateVpnConnectionRequest], - operations_pb2.Operation]: - r"""Return a callable for the create vpn connection method over gRPC. - - Creates a new VPN connection in a given project and - location. - - Returns: - Callable[[~.CreateVpnConnectionRequest], - ~.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_vpn_connection' not in self._stubs: - self._stubs['create_vpn_connection'] = self.grpc_channel.unary_unary( - '/google.cloud.edgecontainer.v1.EdgeContainer/CreateVpnConnection', - request_serializer=service.CreateVpnConnectionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_vpn_connection'] - - @property - def delete_vpn_connection(self) -> Callable[ - [service.DeleteVpnConnectionRequest], - operations_pb2.Operation]: - r"""Return a callable for the delete vpn connection method over gRPC. - - Deletes a single VPN connection. - - Returns: - Callable[[~.DeleteVpnConnectionRequest], - ~.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_vpn_connection' not in self._stubs: - self._stubs['delete_vpn_connection'] = self.grpc_channel.unary_unary( - '/google.cloud.edgecontainer.v1.EdgeContainer/DeleteVpnConnection', - request_serializer=service.DeleteVpnConnectionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_vpn_connection'] - - @property - def get_server_config(self) -> Callable[ - [service.GetServerConfigRequest], - resources.ServerConfig]: - r"""Return a callable for the get server config method over gRPC. - - Gets the server config. - - Returns: - Callable[[~.GetServerConfigRequest], - ~.ServerConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_server_config' not in self._stubs: - self._stubs['get_server_config'] = self.grpc_channel.unary_unary( - '/google.cloud.edgecontainer.v1.EdgeContainer/GetServerConfig', - request_serializer=service.GetServerConfigRequest.serialize, - response_deserializer=resources.ServerConfig.deserialize, - ) - return self._stubs['get_server_config'] - - def close(self): - self.grpc_channel.close() - - @property - def delete_operation( - self, - ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: - r"""Return a callable for the delete_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "delete_operation" not in self._stubs: - self._stubs["delete_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/DeleteOperation", - request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["delete_operation"] - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def list_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_locations" not in self._stubs: - self._stubs["list_locations"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_location" not in self._stubs: - self._stubs["get_location"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'EdgeContainerGrpcTransport', -) diff --git a/owl-bot-staging/google-cloud-edgecontainer/v1/google/cloud/edgecontainer_v1/services/edge_container/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-edgecontainer/v1/google/cloud/edgecontainer_v1/services/edge_container/transports/grpc_asyncio.py deleted file mode 100644 index b7400d380bf8..000000000000 --- a/owl-bot-staging/google-cloud-edgecontainer/v1/google/cloud/edgecontainer_v1/services/edge_container/transports/grpc_asyncio.py +++ /dev/null @@ -1,1143 +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 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 - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.edgecontainer_v1.types import resources -from google.cloud.edgecontainer_v1.types import service -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from .base import EdgeContainerTransport, DEFAULT_CLIENT_INFO -from .grpc import EdgeContainerGrpcTransport - - -class EdgeContainerGrpcAsyncIOTransport(EdgeContainerTransport): - """gRPC AsyncIO backend transport for EdgeContainer. - - EdgeContainer API provides management of Kubernetes Clusters - on Google Edge Cloud deployments. - - 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 = 'edgecontainer.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 = 'edgecontainer.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: 'edgecontainer.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), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsAsyncClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsAsyncClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def list_clusters(self) -> Callable[ - [service.ListClustersRequest], - Awaitable[service.ListClustersResponse]]: - r"""Return a callable for the list clusters method over gRPC. - - Lists Clusters in a given project and location. - - Returns: - Callable[[~.ListClustersRequest], - Awaitable[~.ListClustersResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_clusters' not in self._stubs: - self._stubs['list_clusters'] = self.grpc_channel.unary_unary( - '/google.cloud.edgecontainer.v1.EdgeContainer/ListClusters', - request_serializer=service.ListClustersRequest.serialize, - response_deserializer=service.ListClustersResponse.deserialize, - ) - return self._stubs['list_clusters'] - - @property - def get_cluster(self) -> Callable[ - [service.GetClusterRequest], - Awaitable[resources.Cluster]]: - r"""Return a callable for the get cluster method over gRPC. - - Gets details of a single Cluster. - - Returns: - Callable[[~.GetClusterRequest], - Awaitable[~.Cluster]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_cluster' not in self._stubs: - self._stubs['get_cluster'] = self.grpc_channel.unary_unary( - '/google.cloud.edgecontainer.v1.EdgeContainer/GetCluster', - request_serializer=service.GetClusterRequest.serialize, - response_deserializer=resources.Cluster.deserialize, - ) - return self._stubs['get_cluster'] - - @property - def create_cluster(self) -> Callable[ - [service.CreateClusterRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the create cluster method over gRPC. - - Creates a new Cluster in a given project and - location. - - Returns: - Callable[[~.CreateClusterRequest], - 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_cluster' not in self._stubs: - self._stubs['create_cluster'] = self.grpc_channel.unary_unary( - '/google.cloud.edgecontainer.v1.EdgeContainer/CreateCluster', - request_serializer=service.CreateClusterRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_cluster'] - - @property - def update_cluster(self) -> Callable[ - [service.UpdateClusterRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the update cluster method over gRPC. - - Updates the parameters of a single Cluster. - - Returns: - Callable[[~.UpdateClusterRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'update_cluster' not in self._stubs: - self._stubs['update_cluster'] = self.grpc_channel.unary_unary( - '/google.cloud.edgecontainer.v1.EdgeContainer/UpdateCluster', - request_serializer=service.UpdateClusterRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_cluster'] - - @property - def upgrade_cluster(self) -> Callable[ - [service.UpgradeClusterRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the upgrade cluster method over gRPC. - - Upgrades a single cluster. - - Returns: - Callable[[~.UpgradeClusterRequest], - 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 'upgrade_cluster' not in self._stubs: - self._stubs['upgrade_cluster'] = self.grpc_channel.unary_unary( - '/google.cloud.edgecontainer.v1.EdgeContainer/UpgradeCluster', - request_serializer=service.UpgradeClusterRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['upgrade_cluster'] - - @property - def delete_cluster(self) -> Callable[ - [service.DeleteClusterRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the delete cluster method over gRPC. - - Deletes a single Cluster. - - Returns: - Callable[[~.DeleteClusterRequest], - 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_cluster' not in self._stubs: - self._stubs['delete_cluster'] = self.grpc_channel.unary_unary( - '/google.cloud.edgecontainer.v1.EdgeContainer/DeleteCluster', - request_serializer=service.DeleteClusterRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_cluster'] - - @property - def generate_access_token(self) -> Callable[ - [service.GenerateAccessTokenRequest], - Awaitable[service.GenerateAccessTokenResponse]]: - r"""Return a callable for the generate access token method over gRPC. - - Generates an access token for a Cluster. - - Returns: - Callable[[~.GenerateAccessTokenRequest], - Awaitable[~.GenerateAccessTokenResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_access_token' not in self._stubs: - self._stubs['generate_access_token'] = self.grpc_channel.unary_unary( - '/google.cloud.edgecontainer.v1.EdgeContainer/GenerateAccessToken', - request_serializer=service.GenerateAccessTokenRequest.serialize, - response_deserializer=service.GenerateAccessTokenResponse.deserialize, - ) - return self._stubs['generate_access_token'] - - @property - def generate_offline_credential(self) -> Callable[ - [service.GenerateOfflineCredentialRequest], - Awaitable[service.GenerateOfflineCredentialResponse]]: - r"""Return a callable for the generate offline credential method over gRPC. - - Generates an offline credential for a Cluster. - - Returns: - Callable[[~.GenerateOfflineCredentialRequest], - Awaitable[~.GenerateOfflineCredentialResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_offline_credential' not in self._stubs: - self._stubs['generate_offline_credential'] = self.grpc_channel.unary_unary( - '/google.cloud.edgecontainer.v1.EdgeContainer/GenerateOfflineCredential', - request_serializer=service.GenerateOfflineCredentialRequest.serialize, - response_deserializer=service.GenerateOfflineCredentialResponse.deserialize, - ) - return self._stubs['generate_offline_credential'] - - @property - def list_node_pools(self) -> Callable[ - [service.ListNodePoolsRequest], - Awaitable[service.ListNodePoolsResponse]]: - r"""Return a callable for the list node pools method over gRPC. - - Lists NodePools in a given project and location. - - Returns: - Callable[[~.ListNodePoolsRequest], - Awaitable[~.ListNodePoolsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_node_pools' not in self._stubs: - self._stubs['list_node_pools'] = self.grpc_channel.unary_unary( - '/google.cloud.edgecontainer.v1.EdgeContainer/ListNodePools', - request_serializer=service.ListNodePoolsRequest.serialize, - response_deserializer=service.ListNodePoolsResponse.deserialize, - ) - return self._stubs['list_node_pools'] - - @property - def get_node_pool(self) -> Callable[ - [service.GetNodePoolRequest], - Awaitable[resources.NodePool]]: - r"""Return a callable for the get node pool method over gRPC. - - Gets details of a single NodePool. - - Returns: - Callable[[~.GetNodePoolRequest], - Awaitable[~.NodePool]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_node_pool' not in self._stubs: - self._stubs['get_node_pool'] = self.grpc_channel.unary_unary( - '/google.cloud.edgecontainer.v1.EdgeContainer/GetNodePool', - request_serializer=service.GetNodePoolRequest.serialize, - response_deserializer=resources.NodePool.deserialize, - ) - return self._stubs['get_node_pool'] - - @property - def create_node_pool(self) -> Callable[ - [service.CreateNodePoolRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the create node pool method over gRPC. - - Creates a new NodePool in a given project and - location. - - Returns: - Callable[[~.CreateNodePoolRequest], - 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_node_pool' not in self._stubs: - self._stubs['create_node_pool'] = self.grpc_channel.unary_unary( - '/google.cloud.edgecontainer.v1.EdgeContainer/CreateNodePool', - request_serializer=service.CreateNodePoolRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_node_pool'] - - @property - def update_node_pool(self) -> Callable[ - [service.UpdateNodePoolRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the update node pool method over gRPC. - - Updates the parameters of a single NodePool. - - Returns: - Callable[[~.UpdateNodePoolRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'update_node_pool' not in self._stubs: - self._stubs['update_node_pool'] = self.grpc_channel.unary_unary( - '/google.cloud.edgecontainer.v1.EdgeContainer/UpdateNodePool', - request_serializer=service.UpdateNodePoolRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['update_node_pool'] - - @property - def delete_node_pool(self) -> Callable[ - [service.DeleteNodePoolRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the delete node pool method over gRPC. - - Deletes a single NodePool. - - Returns: - Callable[[~.DeleteNodePoolRequest], - 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_node_pool' not in self._stubs: - self._stubs['delete_node_pool'] = self.grpc_channel.unary_unary( - '/google.cloud.edgecontainer.v1.EdgeContainer/DeleteNodePool', - request_serializer=service.DeleteNodePoolRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_node_pool'] - - @property - def list_machines(self) -> Callable[ - [service.ListMachinesRequest], - Awaitable[service.ListMachinesResponse]]: - r"""Return a callable for the list machines method over gRPC. - - Lists Machines in a given project and location. - - Returns: - Callable[[~.ListMachinesRequest], - Awaitable[~.ListMachinesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_machines' not in self._stubs: - self._stubs['list_machines'] = self.grpc_channel.unary_unary( - '/google.cloud.edgecontainer.v1.EdgeContainer/ListMachines', - request_serializer=service.ListMachinesRequest.serialize, - response_deserializer=service.ListMachinesResponse.deserialize, - ) - return self._stubs['list_machines'] - - @property - def get_machine(self) -> Callable[ - [service.GetMachineRequest], - Awaitable[resources.Machine]]: - r"""Return a callable for the get machine method over gRPC. - - Gets details of a single Machine. - - Returns: - Callable[[~.GetMachineRequest], - Awaitable[~.Machine]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_machine' not in self._stubs: - self._stubs['get_machine'] = self.grpc_channel.unary_unary( - '/google.cloud.edgecontainer.v1.EdgeContainer/GetMachine', - request_serializer=service.GetMachineRequest.serialize, - response_deserializer=resources.Machine.deserialize, - ) - return self._stubs['get_machine'] - - @property - def list_vpn_connections(self) -> Callable[ - [service.ListVpnConnectionsRequest], - Awaitable[service.ListVpnConnectionsResponse]]: - r"""Return a callable for the list vpn connections method over gRPC. - - Lists VPN connections in a given project and - location. - - Returns: - Callable[[~.ListVpnConnectionsRequest], - Awaitable[~.ListVpnConnectionsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_vpn_connections' not in self._stubs: - self._stubs['list_vpn_connections'] = self.grpc_channel.unary_unary( - '/google.cloud.edgecontainer.v1.EdgeContainer/ListVpnConnections', - request_serializer=service.ListVpnConnectionsRequest.serialize, - response_deserializer=service.ListVpnConnectionsResponse.deserialize, - ) - return self._stubs['list_vpn_connections'] - - @property - def get_vpn_connection(self) -> Callable[ - [service.GetVpnConnectionRequest], - Awaitable[resources.VpnConnection]]: - r"""Return a callable for the get vpn connection method over gRPC. - - Gets details of a single VPN connection. - - Returns: - Callable[[~.GetVpnConnectionRequest], - Awaitable[~.VpnConnection]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_vpn_connection' not in self._stubs: - self._stubs['get_vpn_connection'] = self.grpc_channel.unary_unary( - '/google.cloud.edgecontainer.v1.EdgeContainer/GetVpnConnection', - request_serializer=service.GetVpnConnectionRequest.serialize, - response_deserializer=resources.VpnConnection.deserialize, - ) - return self._stubs['get_vpn_connection'] - - @property - def create_vpn_connection(self) -> Callable[ - [service.CreateVpnConnectionRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the create vpn connection method over gRPC. - - Creates a new VPN connection in a given project and - location. - - Returns: - Callable[[~.CreateVpnConnectionRequest], - 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_vpn_connection' not in self._stubs: - self._stubs['create_vpn_connection'] = self.grpc_channel.unary_unary( - '/google.cloud.edgecontainer.v1.EdgeContainer/CreateVpnConnection', - request_serializer=service.CreateVpnConnectionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_vpn_connection'] - - @property - def delete_vpn_connection(self) -> Callable[ - [service.DeleteVpnConnectionRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the delete vpn connection method over gRPC. - - Deletes a single VPN connection. - - Returns: - Callable[[~.DeleteVpnConnectionRequest], - 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_vpn_connection' not in self._stubs: - self._stubs['delete_vpn_connection'] = self.grpc_channel.unary_unary( - '/google.cloud.edgecontainer.v1.EdgeContainer/DeleteVpnConnection', - request_serializer=service.DeleteVpnConnectionRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_vpn_connection'] - - @property - def get_server_config(self) -> Callable[ - [service.GetServerConfigRequest], - Awaitable[resources.ServerConfig]]: - r"""Return a callable for the get server config method over gRPC. - - Gets the server config. - - Returns: - Callable[[~.GetServerConfigRequest], - Awaitable[~.ServerConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_server_config' not in self._stubs: - self._stubs['get_server_config'] = self.grpc_channel.unary_unary( - '/google.cloud.edgecontainer.v1.EdgeContainer/GetServerConfig', - request_serializer=service.GetServerConfigRequest.serialize, - response_deserializer=resources.ServerConfig.deserialize, - ) - return self._stubs['get_server_config'] - - 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_clusters: self._wrap_method( - self.list_clusters, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_cluster: self._wrap_method( - self.get_cluster, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.create_cluster: self._wrap_method( - self.create_cluster, - default_timeout=60.0, - client_info=client_info, - ), - self.update_cluster: self._wrap_method( - self.update_cluster, - default_timeout=60.0, - client_info=client_info, - ), - self.upgrade_cluster: self._wrap_method( - self.upgrade_cluster, - default_timeout=60.0, - client_info=client_info, - ), - self.delete_cluster: self._wrap_method( - self.delete_cluster, - default_timeout=60.0, - client_info=client_info, - ), - self.generate_access_token: self._wrap_method( - self.generate_access_token, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.generate_offline_credential: self._wrap_method( - self.generate_offline_credential, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_node_pools: self._wrap_method( - self.list_node_pools, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_node_pool: self._wrap_method( - self.get_node_pool, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.create_node_pool: self._wrap_method( - self.create_node_pool, - default_timeout=60.0, - client_info=client_info, - ), - self.update_node_pool: self._wrap_method( - self.update_node_pool, - default_timeout=60.0, - client_info=client_info, - ), - self.delete_node_pool: self._wrap_method( - self.delete_node_pool, - default_timeout=60.0, - client_info=client_info, - ), - self.list_machines: self._wrap_method( - self.list_machines, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_machine: self._wrap_method( - self.get_machine, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_vpn_connections: self._wrap_method( - self.list_vpn_connections, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_vpn_connection: self._wrap_method( - self.get_vpn_connection, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.create_vpn_connection: self._wrap_method( - self.create_vpn_connection, - default_timeout=60.0, - client_info=client_info, - ), - self.delete_vpn_connection: self._wrap_method( - self.delete_vpn_connection, - default_timeout=60.0, - client_info=client_info, - ), - self.get_server_config: self._wrap_method( - self.get_server_config, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_location: self._wrap_method( - self.get_location, - default_timeout=None, - client_info=client_info, - ), - self.list_locations: self._wrap_method( - self.list_locations, - default_timeout=None, - client_info=client_info, - ), - self.cancel_operation: self._wrap_method( - self.cancel_operation, - default_timeout=None, - client_info=client_info, - ), - self.delete_operation: self._wrap_method( - self.delete_operation, - default_timeout=None, - client_info=client_info, - ), - self.get_operation: self._wrap_method( - self.get_operation, - default_timeout=None, - client_info=client_info, - ), - self.list_operations: self._wrap_method( - self.list_operations, - default_timeout=None, - client_info=client_info, - ), - } - - def _wrap_method(self, func, *args, **kwargs): - if self._wrap_with_kind: # pragma: NO COVER - kwargs["kind"] = self.kind - return gapic_v1.method_async.wrap_method(func, *args, **kwargs) - - def close(self): - return self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc_asyncio" - - @property - def delete_operation( - self, - ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: - r"""Return a callable for the delete_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "delete_operation" not in self._stubs: - self._stubs["delete_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/DeleteOperation", - request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["delete_operation"] - - @property - def cancel_operation( - self, - ) -> Callable[[operations_pb2.CancelOperationRequest], None]: - r"""Return a callable for the cancel_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "cancel_operation" not in self._stubs: - self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/CancelOperation", - request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, - response_deserializer=None, - ) - return self._stubs["cancel_operation"] - - @property - def get_operation( - self, - ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: - r"""Return a callable for the get_operation method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_operation" not in self._stubs: - self._stubs["get_operation"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/GetOperation", - request_serializer=operations_pb2.GetOperationRequest.SerializeToString, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs["get_operation"] - - @property - def list_operations( - self, - ) -> Callable[[operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse]: - r"""Return a callable for the list_operations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_operations" not in self._stubs: - self._stubs["list_operations"] = self.grpc_channel.unary_unary( - "/google.longrunning.Operations/ListOperations", - request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, - response_deserializer=operations_pb2.ListOperationsResponse.FromString, - ) - return self._stubs["list_operations"] - - @property - def list_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_locations" not in self._stubs: - self._stubs["list_locations"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_location" not in self._stubs: - self._stubs["get_location"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - -__all__ = ( - 'EdgeContainerGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-cloud-edgecontainer/v1/google/cloud/edgecontainer_v1/services/edge_container/transports/rest.py b/owl-bot-staging/google-cloud-edgecontainer/v1/google/cloud/edgecontainer_v1/services/edge_container/transports/rest.py deleted file mode 100644 index cde149c70787..000000000000 --- a/owl-bot-staging/google-cloud-edgecontainer/v1/google/cloud/edgecontainer_v1/services/edge_container/transports/rest.py +++ /dev/null @@ -1,2899 +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.auth.transport.requests import AuthorizedSession # type: ignore -import json # 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.cloud.location import locations_pb2 # type: ignore - -from requests import __version__ as requests_version -import dataclasses -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - - -from google.cloud.edgecontainer_v1.types import resources -from google.cloud.edgecontainer_v1.types import service -from google.longrunning import operations_pb2 # type: ignore - - -from .rest_base import _BaseEdgeContainerRestTransport -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 - - -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 EdgeContainerRestInterceptor: - """Interceptor for EdgeContainer. - - 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 EdgeContainerRestTransport. - - .. code-block:: python - class MyCustomEdgeContainerInterceptor(EdgeContainerRestInterceptor): - def pre_create_cluster(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_cluster(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_node_pool(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_node_pool(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_vpn_connection(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_vpn_connection(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_cluster(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_delete_cluster(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_node_pool(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_delete_node_pool(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_vpn_connection(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_delete_vpn_connection(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_generate_access_token(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_generate_access_token(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_generate_offline_credential(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_generate_offline_credential(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_cluster(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_cluster(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_machine(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_machine(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_node_pool(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_node_pool(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_server_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_server_config(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_vpn_connection(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_vpn_connection(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_clusters(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_clusters(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_machines(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_machines(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_node_pools(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_node_pools(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_vpn_connections(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_vpn_connections(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_cluster(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_cluster(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_node_pool(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_node_pool(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_upgrade_cluster(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_upgrade_cluster(self, response): - logging.log(f"Received response: {response}") - return response - - transport = EdgeContainerRestTransport(interceptor=MyCustomEdgeContainerInterceptor()) - client = EdgeContainerClient(transport=transport) - - - """ - def pre_create_cluster(self, request: service.CreateClusterRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.CreateClusterRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_cluster - - Override in a subclass to manipulate the request or metadata - before they are sent to the EdgeContainer server. - """ - return request, metadata - - def post_create_cluster(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for create_cluster - - Override in a subclass to manipulate the response - after it is returned by the EdgeContainer server but before - it is returned to user code. - """ - return response - - def pre_create_node_pool(self, request: service.CreateNodePoolRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.CreateNodePoolRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_node_pool - - Override in a subclass to manipulate the request or metadata - before they are sent to the EdgeContainer server. - """ - return request, metadata - - def post_create_node_pool(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for create_node_pool - - Override in a subclass to manipulate the response - after it is returned by the EdgeContainer server but before - it is returned to user code. - """ - return response - - def pre_create_vpn_connection(self, request: service.CreateVpnConnectionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.CreateVpnConnectionRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_vpn_connection - - Override in a subclass to manipulate the request or metadata - before they are sent to the EdgeContainer server. - """ - return request, metadata - - def post_create_vpn_connection(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for create_vpn_connection - - Override in a subclass to manipulate the response - after it is returned by the EdgeContainer server but before - it is returned to user code. - """ - return response - - def pre_delete_cluster(self, request: service.DeleteClusterRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.DeleteClusterRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_cluster - - Override in a subclass to manipulate the request or metadata - before they are sent to the EdgeContainer server. - """ - return request, metadata - - def post_delete_cluster(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for delete_cluster - - Override in a subclass to manipulate the response - after it is returned by the EdgeContainer server but before - it is returned to user code. - """ - return response - - def pre_delete_node_pool(self, request: service.DeleteNodePoolRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.DeleteNodePoolRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_node_pool - - Override in a subclass to manipulate the request or metadata - before they are sent to the EdgeContainer server. - """ - return request, metadata - - def post_delete_node_pool(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for delete_node_pool - - Override in a subclass to manipulate the response - after it is returned by the EdgeContainer server but before - it is returned to user code. - """ - return response - - def pre_delete_vpn_connection(self, request: service.DeleteVpnConnectionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.DeleteVpnConnectionRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_vpn_connection - - Override in a subclass to manipulate the request or metadata - before they are sent to the EdgeContainer server. - """ - return request, metadata - - def post_delete_vpn_connection(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for delete_vpn_connection - - Override in a subclass to manipulate the response - after it is returned by the EdgeContainer server but before - it is returned to user code. - """ - return response - - def pre_generate_access_token(self, request: service.GenerateAccessTokenRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.GenerateAccessTokenRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for generate_access_token - - Override in a subclass to manipulate the request or metadata - before they are sent to the EdgeContainer server. - """ - return request, metadata - - def post_generate_access_token(self, response: service.GenerateAccessTokenResponse) -> service.GenerateAccessTokenResponse: - """Post-rpc interceptor for generate_access_token - - Override in a subclass to manipulate the response - after it is returned by the EdgeContainer server but before - it is returned to user code. - """ - return response - - def pre_generate_offline_credential(self, request: service.GenerateOfflineCredentialRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.GenerateOfflineCredentialRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for generate_offline_credential - - Override in a subclass to manipulate the request or metadata - before they are sent to the EdgeContainer server. - """ - return request, metadata - - def post_generate_offline_credential(self, response: service.GenerateOfflineCredentialResponse) -> service.GenerateOfflineCredentialResponse: - """Post-rpc interceptor for generate_offline_credential - - Override in a subclass to manipulate the response - after it is returned by the EdgeContainer server but before - it is returned to user code. - """ - return response - - def pre_get_cluster(self, request: service.GetClusterRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.GetClusterRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_cluster - - Override in a subclass to manipulate the request or metadata - before they are sent to the EdgeContainer server. - """ - return request, metadata - - def post_get_cluster(self, response: resources.Cluster) -> resources.Cluster: - """Post-rpc interceptor for get_cluster - - Override in a subclass to manipulate the response - after it is returned by the EdgeContainer server but before - it is returned to user code. - """ - return response - - def pre_get_machine(self, request: service.GetMachineRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.GetMachineRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_machine - - Override in a subclass to manipulate the request or metadata - before they are sent to the EdgeContainer server. - """ - return request, metadata - - def post_get_machine(self, response: resources.Machine) -> resources.Machine: - """Post-rpc interceptor for get_machine - - Override in a subclass to manipulate the response - after it is returned by the EdgeContainer server but before - it is returned to user code. - """ - return response - - def pre_get_node_pool(self, request: service.GetNodePoolRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.GetNodePoolRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_node_pool - - Override in a subclass to manipulate the request or metadata - before they are sent to the EdgeContainer server. - """ - return request, metadata - - def post_get_node_pool(self, response: resources.NodePool) -> resources.NodePool: - """Post-rpc interceptor for get_node_pool - - Override in a subclass to manipulate the response - after it is returned by the EdgeContainer server but before - it is returned to user code. - """ - return response - - def pre_get_server_config(self, request: service.GetServerConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.GetServerConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_server_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the EdgeContainer server. - """ - return request, metadata - - def post_get_server_config(self, response: resources.ServerConfig) -> resources.ServerConfig: - """Post-rpc interceptor for get_server_config - - Override in a subclass to manipulate the response - after it is returned by the EdgeContainer server but before - it is returned to user code. - """ - return response - - def pre_get_vpn_connection(self, request: service.GetVpnConnectionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.GetVpnConnectionRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_vpn_connection - - Override in a subclass to manipulate the request or metadata - before they are sent to the EdgeContainer server. - """ - return request, metadata - - def post_get_vpn_connection(self, response: resources.VpnConnection) -> resources.VpnConnection: - """Post-rpc interceptor for get_vpn_connection - - Override in a subclass to manipulate the response - after it is returned by the EdgeContainer server but before - it is returned to user code. - """ - return response - - def pre_list_clusters(self, request: service.ListClustersRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.ListClustersRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_clusters - - Override in a subclass to manipulate the request or metadata - before they are sent to the EdgeContainer server. - """ - return request, metadata - - def post_list_clusters(self, response: service.ListClustersResponse) -> service.ListClustersResponse: - """Post-rpc interceptor for list_clusters - - Override in a subclass to manipulate the response - after it is returned by the EdgeContainer server but before - it is returned to user code. - """ - return response - - def pre_list_machines(self, request: service.ListMachinesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.ListMachinesRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_machines - - Override in a subclass to manipulate the request or metadata - before they are sent to the EdgeContainer server. - """ - return request, metadata - - def post_list_machines(self, response: service.ListMachinesResponse) -> service.ListMachinesResponse: - """Post-rpc interceptor for list_machines - - Override in a subclass to manipulate the response - after it is returned by the EdgeContainer server but before - it is returned to user code. - """ - return response - - def pre_list_node_pools(self, request: service.ListNodePoolsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.ListNodePoolsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_node_pools - - Override in a subclass to manipulate the request or metadata - before they are sent to the EdgeContainer server. - """ - return request, metadata - - def post_list_node_pools(self, response: service.ListNodePoolsResponse) -> service.ListNodePoolsResponse: - """Post-rpc interceptor for list_node_pools - - Override in a subclass to manipulate the response - after it is returned by the EdgeContainer server but before - it is returned to user code. - """ - return response - - def pre_list_vpn_connections(self, request: service.ListVpnConnectionsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.ListVpnConnectionsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_vpn_connections - - Override in a subclass to manipulate the request or metadata - before they are sent to the EdgeContainer server. - """ - return request, metadata - - def post_list_vpn_connections(self, response: service.ListVpnConnectionsResponse) -> service.ListVpnConnectionsResponse: - """Post-rpc interceptor for list_vpn_connections - - Override in a subclass to manipulate the response - after it is returned by the EdgeContainer server but before - it is returned to user code. - """ - return response - - def pre_update_cluster(self, request: service.UpdateClusterRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.UpdateClusterRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_cluster - - Override in a subclass to manipulate the request or metadata - before they are sent to the EdgeContainer server. - """ - return request, metadata - - def post_update_cluster(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for update_cluster - - Override in a subclass to manipulate the response - after it is returned by the EdgeContainer server but before - it is returned to user code. - """ - return response - - def pre_update_node_pool(self, request: service.UpdateNodePoolRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.UpdateNodePoolRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_node_pool - - Override in a subclass to manipulate the request or metadata - before they are sent to the EdgeContainer server. - """ - return request, metadata - - def post_update_node_pool(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for update_node_pool - - Override in a subclass to manipulate the response - after it is returned by the EdgeContainer server but before - it is returned to user code. - """ - return response - - def pre_upgrade_cluster(self, request: service.UpgradeClusterRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.UpgradeClusterRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for upgrade_cluster - - Override in a subclass to manipulate the request or metadata - before they are sent to the EdgeContainer server. - """ - return request, metadata - - def post_upgrade_cluster(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for upgrade_cluster - - Override in a subclass to manipulate the response - after it is returned by the EdgeContainer server but before - it is returned to user code. - """ - return response - - def pre_get_location( - self, request: locations_pb2.GetLocationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[locations_pb2.GetLocationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_location - - Override in a subclass to manipulate the request or metadata - before they are sent to the EdgeContainer server. - """ - return request, metadata - - def post_get_location( - self, response: locations_pb2.Location - ) -> locations_pb2.Location: - """Post-rpc interceptor for get_location - - Override in a subclass to manipulate the response - after it is returned by the EdgeContainer server but before - it is returned to user code. - """ - return response - - def pre_list_locations( - self, request: locations_pb2.ListLocationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[locations_pb2.ListLocationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_locations - - Override in a subclass to manipulate the request or metadata - before they are sent to the EdgeContainer server. - """ - return request, metadata - - def post_list_locations( - self, response: locations_pb2.ListLocationsResponse - ) -> locations_pb2.ListLocationsResponse: - """Post-rpc interceptor for list_locations - - Override in a subclass to manipulate the response - after it is returned by the EdgeContainer server but before - it is returned to user code. - """ - return response - - def pre_cancel_operation( - self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the EdgeContainer server. - """ - return request, metadata - - def post_cancel_operation( - self, response: None - ) -> None: - """Post-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the response - after it is returned by the EdgeContainer server but before - it is returned to user code. - """ - return response - - def pre_delete_operation( - self, request: operations_pb2.DeleteOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the EdgeContainer server. - """ - return request, metadata - - def post_delete_operation( - self, response: None - ) -> None: - """Post-rpc interceptor for delete_operation - - Override in a subclass to manipulate the response - after it is returned by the EdgeContainer server but before - it is returned to user code. - """ - return response - - def pre_get_operation( - self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the EdgeContainer server. - """ - return request, metadata - - def post_get_operation( - self, response: operations_pb2.Operation - ) -> operations_pb2.Operation: - """Post-rpc interceptor for get_operation - - Override in a subclass to manipulate the response - after it is returned by the EdgeContainer server but before - it is returned to user code. - """ - return response - - def pre_list_operations( - self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_operations - - Override in a subclass to manipulate the request or metadata - before they are sent to the EdgeContainer 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 EdgeContainer server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class EdgeContainerRestStub: - _session: AuthorizedSession - _host: str - _interceptor: EdgeContainerRestInterceptor - - -class EdgeContainerRestTransport(_BaseEdgeContainerRestTransport): - """REST backend synchronous transport for EdgeContainer. - - EdgeContainer API provides management of Kubernetes Clusters - on Google Edge Cloud deployments. - - 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 = 'edgecontainer.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[EdgeContainerRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'edgecontainer.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 EdgeContainerRestInterceptor() - self._prep_wrapped_messages(client_info) - - @property - def operations_client(self) -> operations_v1.AbstractOperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Only create a new client if we do not already have one. - if self._operations_client is None: - http_options: Dict[str, List[Dict[str, str]]] = { - 'google.longrunning.Operations.CancelOperation': [ - { - 'method': 'post', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}:cancel', - 'body': '*', - }, - ], - 'google.longrunning.Operations.DeleteOperation': [ - { - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}', - }, - ], - 'google.longrunning.Operations.GetOperation': [ - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}', - }, - ], - 'google.longrunning.Operations.ListOperations': [ - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*}/operations', - }, - ], - } - - rest_transport = operations_v1.OperationsRestTransport( - host=self._host, - # use the credentials which are saved - credentials=self._credentials, - scopes=self._scopes, - http_options=http_options, - path_prefix="v1") - - self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) - - # Return the client from cache. - return self._operations_client - - class _CreateCluster(_BaseEdgeContainerRestTransport._BaseCreateCluster, EdgeContainerRestStub): - def __hash__(self): - return hash("EdgeContainerRestTransport.CreateCluster") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: service.CreateClusterRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the create cluster method over HTTP. - - Args: - request (~.service.CreateClusterRequest): - The request object. Creates a cluster. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseEdgeContainerRestTransport._BaseCreateCluster._get_http_options() - request, metadata = self._interceptor.pre_create_cluster(request, metadata) - transcoded_request = _BaseEdgeContainerRestTransport._BaseCreateCluster._get_transcoded_request(http_options, request) - - body = _BaseEdgeContainerRestTransport._BaseCreateCluster._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseEdgeContainerRestTransport._BaseCreateCluster._get_query_params_json(transcoded_request) - - # Send the request - response = EdgeContainerRestTransport._CreateCluster._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_cluster(resp) - return resp - - class _CreateNodePool(_BaseEdgeContainerRestTransport._BaseCreateNodePool, EdgeContainerRestStub): - def __hash__(self): - return hash("EdgeContainerRestTransport.CreateNodePool") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: service.CreateNodePoolRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the create node pool method over HTTP. - - Args: - request (~.service.CreateNodePoolRequest): - The request object. Creates a node pool. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseEdgeContainerRestTransport._BaseCreateNodePool._get_http_options() - request, metadata = self._interceptor.pre_create_node_pool(request, metadata) - transcoded_request = _BaseEdgeContainerRestTransport._BaseCreateNodePool._get_transcoded_request(http_options, request) - - body = _BaseEdgeContainerRestTransport._BaseCreateNodePool._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseEdgeContainerRestTransport._BaseCreateNodePool._get_query_params_json(transcoded_request) - - # Send the request - response = EdgeContainerRestTransport._CreateNodePool._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_node_pool(resp) - return resp - - class _CreateVpnConnection(_BaseEdgeContainerRestTransport._BaseCreateVpnConnection, EdgeContainerRestStub): - def __hash__(self): - return hash("EdgeContainerRestTransport.CreateVpnConnection") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: service.CreateVpnConnectionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the create vpn connection method over HTTP. - - Args: - request (~.service.CreateVpnConnectionRequest): - The request object. Creates a VPN connection. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseEdgeContainerRestTransport._BaseCreateVpnConnection._get_http_options() - request, metadata = self._interceptor.pre_create_vpn_connection(request, metadata) - transcoded_request = _BaseEdgeContainerRestTransport._BaseCreateVpnConnection._get_transcoded_request(http_options, request) - - body = _BaseEdgeContainerRestTransport._BaseCreateVpnConnection._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseEdgeContainerRestTransport._BaseCreateVpnConnection._get_query_params_json(transcoded_request) - - # Send the request - response = EdgeContainerRestTransport._CreateVpnConnection._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_vpn_connection(resp) - return resp - - class _DeleteCluster(_BaseEdgeContainerRestTransport._BaseDeleteCluster, EdgeContainerRestStub): - def __hash__(self): - return hash("EdgeContainerRestTransport.DeleteCluster") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: service.DeleteClusterRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the delete cluster method over HTTP. - - Args: - request (~.service.DeleteClusterRequest): - The request object. Deletes a cluster. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseEdgeContainerRestTransport._BaseDeleteCluster._get_http_options() - request, metadata = self._interceptor.pre_delete_cluster(request, metadata) - transcoded_request = _BaseEdgeContainerRestTransport._BaseDeleteCluster._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseEdgeContainerRestTransport._BaseDeleteCluster._get_query_params_json(transcoded_request) - - # Send the request - response = EdgeContainerRestTransport._DeleteCluster._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_cluster(resp) - return resp - - class _DeleteNodePool(_BaseEdgeContainerRestTransport._BaseDeleteNodePool, EdgeContainerRestStub): - def __hash__(self): - return hash("EdgeContainerRestTransport.DeleteNodePool") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: service.DeleteNodePoolRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the delete node pool method over HTTP. - - Args: - request (~.service.DeleteNodePoolRequest): - The request object. Deletes a node pool. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseEdgeContainerRestTransport._BaseDeleteNodePool._get_http_options() - request, metadata = self._interceptor.pre_delete_node_pool(request, metadata) - transcoded_request = _BaseEdgeContainerRestTransport._BaseDeleteNodePool._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseEdgeContainerRestTransport._BaseDeleteNodePool._get_query_params_json(transcoded_request) - - # Send the request - response = EdgeContainerRestTransport._DeleteNodePool._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_node_pool(resp) - return resp - - class _DeleteVpnConnection(_BaseEdgeContainerRestTransport._BaseDeleteVpnConnection, EdgeContainerRestStub): - def __hash__(self): - return hash("EdgeContainerRestTransport.DeleteVpnConnection") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: service.DeleteVpnConnectionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the delete vpn connection method over HTTP. - - Args: - request (~.service.DeleteVpnConnectionRequest): - The request object. Deletes a vpn connection. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseEdgeContainerRestTransport._BaseDeleteVpnConnection._get_http_options() - request, metadata = self._interceptor.pre_delete_vpn_connection(request, metadata) - transcoded_request = _BaseEdgeContainerRestTransport._BaseDeleteVpnConnection._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseEdgeContainerRestTransport._BaseDeleteVpnConnection._get_query_params_json(transcoded_request) - - # Send the request - response = EdgeContainerRestTransport._DeleteVpnConnection._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_vpn_connection(resp) - return resp - - class _GenerateAccessToken(_BaseEdgeContainerRestTransport._BaseGenerateAccessToken, EdgeContainerRestStub): - def __hash__(self): - return hash("EdgeContainerRestTransport.GenerateAccessToken") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: service.GenerateAccessTokenRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> service.GenerateAccessTokenResponse: - r"""Call the generate access token method over HTTP. - - Args: - request (~.service.GenerateAccessTokenRequest): - The request object. Generates an access token for a - cluster. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.service.GenerateAccessTokenResponse: - An access token for a cluster. - """ - - http_options = _BaseEdgeContainerRestTransport._BaseGenerateAccessToken._get_http_options() - request, metadata = self._interceptor.pre_generate_access_token(request, metadata) - transcoded_request = _BaseEdgeContainerRestTransport._BaseGenerateAccessToken._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseEdgeContainerRestTransport._BaseGenerateAccessToken._get_query_params_json(transcoded_request) - - # Send the request - response = EdgeContainerRestTransport._GenerateAccessToken._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.GenerateAccessTokenResponse() - pb_resp = service.GenerateAccessTokenResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_generate_access_token(resp) - return resp - - class _GenerateOfflineCredential(_BaseEdgeContainerRestTransport._BaseGenerateOfflineCredential, EdgeContainerRestStub): - def __hash__(self): - return hash("EdgeContainerRestTransport.GenerateOfflineCredential") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: service.GenerateOfflineCredentialRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> service.GenerateOfflineCredentialResponse: - r"""Call the generate offline - credential method over HTTP. - - Args: - request (~.service.GenerateOfflineCredentialRequest): - The request object. Generates an offline - credential(offline) for a cluster. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.service.GenerateOfflineCredentialResponse: - An offline credential for a cluster. - """ - - http_options = _BaseEdgeContainerRestTransport._BaseGenerateOfflineCredential._get_http_options() - request, metadata = self._interceptor.pre_generate_offline_credential(request, metadata) - transcoded_request = _BaseEdgeContainerRestTransport._BaseGenerateOfflineCredential._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseEdgeContainerRestTransport._BaseGenerateOfflineCredential._get_query_params_json(transcoded_request) - - # Send the request - response = EdgeContainerRestTransport._GenerateOfflineCredential._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.GenerateOfflineCredentialResponse() - pb_resp = service.GenerateOfflineCredentialResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_generate_offline_credential(resp) - return resp - - class _GetCluster(_BaseEdgeContainerRestTransport._BaseGetCluster, EdgeContainerRestStub): - def __hash__(self): - return hash("EdgeContainerRestTransport.GetCluster") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: service.GetClusterRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> resources.Cluster: - r"""Call the get cluster method over HTTP. - - Args: - request (~.service.GetClusterRequest): - The request object. Gets a cluster. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.resources.Cluster: - A Google Distributed Cloud Edge - Kubernetes cluster. - - """ - - http_options = _BaseEdgeContainerRestTransport._BaseGetCluster._get_http_options() - request, metadata = self._interceptor.pre_get_cluster(request, metadata) - transcoded_request = _BaseEdgeContainerRestTransport._BaseGetCluster._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseEdgeContainerRestTransport._BaseGetCluster._get_query_params_json(transcoded_request) - - # Send the request - response = EdgeContainerRestTransport._GetCluster._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.Cluster() - pb_resp = resources.Cluster.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_cluster(resp) - return resp - - class _GetMachine(_BaseEdgeContainerRestTransport._BaseGetMachine, EdgeContainerRestStub): - def __hash__(self): - return hash("EdgeContainerRestTransport.GetMachine") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: service.GetMachineRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> resources.Machine: - r"""Call the get machine method over HTTP. - - Args: - request (~.service.GetMachineRequest): - The request object. Gets a machine. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.resources.Machine: - A Google Distributed Cloud Edge - machine capable of acting as a - Kubernetes node. - - """ - - http_options = _BaseEdgeContainerRestTransport._BaseGetMachine._get_http_options() - request, metadata = self._interceptor.pre_get_machine(request, metadata) - transcoded_request = _BaseEdgeContainerRestTransport._BaseGetMachine._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseEdgeContainerRestTransport._BaseGetMachine._get_query_params_json(transcoded_request) - - # Send the request - response = EdgeContainerRestTransport._GetMachine._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.Machine() - pb_resp = resources.Machine.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_machine(resp) - return resp - - class _GetNodePool(_BaseEdgeContainerRestTransport._BaseGetNodePool, EdgeContainerRestStub): - def __hash__(self): - return hash("EdgeContainerRestTransport.GetNodePool") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: service.GetNodePoolRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> resources.NodePool: - r"""Call the get node pool method over HTTP. - - Args: - request (~.service.GetNodePoolRequest): - The request object. Gets a node pool. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.resources.NodePool: - A set of Kubernetes nodes in a - cluster with common configuration and - specification. - - """ - - http_options = _BaseEdgeContainerRestTransport._BaseGetNodePool._get_http_options() - request, metadata = self._interceptor.pre_get_node_pool(request, metadata) - transcoded_request = _BaseEdgeContainerRestTransport._BaseGetNodePool._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseEdgeContainerRestTransport._BaseGetNodePool._get_query_params_json(transcoded_request) - - # Send the request - response = EdgeContainerRestTransport._GetNodePool._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.NodePool() - pb_resp = resources.NodePool.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_node_pool(resp) - return resp - - class _GetServerConfig(_BaseEdgeContainerRestTransport._BaseGetServerConfig, EdgeContainerRestStub): - def __hash__(self): - return hash("EdgeContainerRestTransport.GetServerConfig") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: service.GetServerConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> resources.ServerConfig: - r"""Call the get server config method over HTTP. - - Args: - request (~.service.GetServerConfigRequest): - The request object. Gets the server 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. - - Returns: - ~.resources.ServerConfig: - Server configuration for supported - versions and release channels. - - """ - - http_options = _BaseEdgeContainerRestTransport._BaseGetServerConfig._get_http_options() - request, metadata = self._interceptor.pre_get_server_config(request, metadata) - transcoded_request = _BaseEdgeContainerRestTransport._BaseGetServerConfig._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseEdgeContainerRestTransport._BaseGetServerConfig._get_query_params_json(transcoded_request) - - # Send the request - response = EdgeContainerRestTransport._GetServerConfig._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.ServerConfig() - pb_resp = resources.ServerConfig.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_server_config(resp) - return resp - - class _GetVpnConnection(_BaseEdgeContainerRestTransport._BaseGetVpnConnection, EdgeContainerRestStub): - def __hash__(self): - return hash("EdgeContainerRestTransport.GetVpnConnection") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: service.GetVpnConnectionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> resources.VpnConnection: - r"""Call the get vpn connection method over HTTP. - - Args: - request (~.service.GetVpnConnectionRequest): - The request object. Gets a VPN connection. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.resources.VpnConnection: - A VPN connection . - """ - - http_options = _BaseEdgeContainerRestTransport._BaseGetVpnConnection._get_http_options() - request, metadata = self._interceptor.pre_get_vpn_connection(request, metadata) - transcoded_request = _BaseEdgeContainerRestTransport._BaseGetVpnConnection._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseEdgeContainerRestTransport._BaseGetVpnConnection._get_query_params_json(transcoded_request) - - # Send the request - response = EdgeContainerRestTransport._GetVpnConnection._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.VpnConnection() - pb_resp = resources.VpnConnection.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_vpn_connection(resp) - return resp - - class _ListClusters(_BaseEdgeContainerRestTransport._BaseListClusters, EdgeContainerRestStub): - def __hash__(self): - return hash("EdgeContainerRestTransport.ListClusters") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: service.ListClustersRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> service.ListClustersResponse: - r"""Call the list clusters method over HTTP. - - Args: - request (~.service.ListClustersRequest): - The request object. Lists clusters in a location. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.service.ListClustersResponse: - List of clusters in a location. - """ - - http_options = _BaseEdgeContainerRestTransport._BaseListClusters._get_http_options() - request, metadata = self._interceptor.pre_list_clusters(request, metadata) - transcoded_request = _BaseEdgeContainerRestTransport._BaseListClusters._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseEdgeContainerRestTransport._BaseListClusters._get_query_params_json(transcoded_request) - - # Send the request - response = EdgeContainerRestTransport._ListClusters._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.ListClustersResponse() - pb_resp = service.ListClustersResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_clusters(resp) - return resp - - class _ListMachines(_BaseEdgeContainerRestTransport._BaseListMachines, EdgeContainerRestStub): - def __hash__(self): - return hash("EdgeContainerRestTransport.ListMachines") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: service.ListMachinesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> service.ListMachinesResponse: - r"""Call the list machines method over HTTP. - - Args: - request (~.service.ListMachinesRequest): - The request object. Lists machines in a site. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.service.ListMachinesResponse: - List of machines in a site. - """ - - http_options = _BaseEdgeContainerRestTransport._BaseListMachines._get_http_options() - request, metadata = self._interceptor.pre_list_machines(request, metadata) - transcoded_request = _BaseEdgeContainerRestTransport._BaseListMachines._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseEdgeContainerRestTransport._BaseListMachines._get_query_params_json(transcoded_request) - - # Send the request - response = EdgeContainerRestTransport._ListMachines._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.ListMachinesResponse() - pb_resp = service.ListMachinesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_machines(resp) - return resp - - class _ListNodePools(_BaseEdgeContainerRestTransport._BaseListNodePools, EdgeContainerRestStub): - def __hash__(self): - return hash("EdgeContainerRestTransport.ListNodePools") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: service.ListNodePoolsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> service.ListNodePoolsResponse: - r"""Call the list node pools method over HTTP. - - Args: - request (~.service.ListNodePoolsRequest): - The request object. Lists node pools in a cluster. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.service.ListNodePoolsResponse: - List of node pools in a cluster. - """ - - http_options = _BaseEdgeContainerRestTransport._BaseListNodePools._get_http_options() - request, metadata = self._interceptor.pre_list_node_pools(request, metadata) - transcoded_request = _BaseEdgeContainerRestTransport._BaseListNodePools._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseEdgeContainerRestTransport._BaseListNodePools._get_query_params_json(transcoded_request) - - # Send the request - response = EdgeContainerRestTransport._ListNodePools._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.ListNodePoolsResponse() - pb_resp = service.ListNodePoolsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_node_pools(resp) - return resp - - class _ListVpnConnections(_BaseEdgeContainerRestTransport._BaseListVpnConnections, EdgeContainerRestStub): - def __hash__(self): - return hash("EdgeContainerRestTransport.ListVpnConnections") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: service.ListVpnConnectionsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> service.ListVpnConnectionsResponse: - r"""Call the list vpn connections method over HTTP. - - Args: - request (~.service.ListVpnConnectionsRequest): - The request object. Lists VPN connections. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.service.ListVpnConnectionsResponse: - List of VPN connections in a - location. - - """ - - http_options = _BaseEdgeContainerRestTransport._BaseListVpnConnections._get_http_options() - request, metadata = self._interceptor.pre_list_vpn_connections(request, metadata) - transcoded_request = _BaseEdgeContainerRestTransport._BaseListVpnConnections._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseEdgeContainerRestTransport._BaseListVpnConnections._get_query_params_json(transcoded_request) - - # Send the request - response = EdgeContainerRestTransport._ListVpnConnections._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.ListVpnConnectionsResponse() - pb_resp = service.ListVpnConnectionsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_vpn_connections(resp) - return resp - - class _UpdateCluster(_BaseEdgeContainerRestTransport._BaseUpdateCluster, EdgeContainerRestStub): - def __hash__(self): - return hash("EdgeContainerRestTransport.UpdateCluster") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: service.UpdateClusterRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the update cluster method over HTTP. - - Args: - request (~.service.UpdateClusterRequest): - The request object. Updates a cluster. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseEdgeContainerRestTransport._BaseUpdateCluster._get_http_options() - request, metadata = self._interceptor.pre_update_cluster(request, metadata) - transcoded_request = _BaseEdgeContainerRestTransport._BaseUpdateCluster._get_transcoded_request(http_options, request) - - body = _BaseEdgeContainerRestTransport._BaseUpdateCluster._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseEdgeContainerRestTransport._BaseUpdateCluster._get_query_params_json(transcoded_request) - - # Send the request - response = EdgeContainerRestTransport._UpdateCluster._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_cluster(resp) - return resp - - class _UpdateNodePool(_BaseEdgeContainerRestTransport._BaseUpdateNodePool, EdgeContainerRestStub): - def __hash__(self): - return hash("EdgeContainerRestTransport.UpdateNodePool") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: service.UpdateNodePoolRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the update node pool method over HTTP. - - Args: - request (~.service.UpdateNodePoolRequest): - The request object. Updates a node pool. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseEdgeContainerRestTransport._BaseUpdateNodePool._get_http_options() - request, metadata = self._interceptor.pre_update_node_pool(request, metadata) - transcoded_request = _BaseEdgeContainerRestTransport._BaseUpdateNodePool._get_transcoded_request(http_options, request) - - body = _BaseEdgeContainerRestTransport._BaseUpdateNodePool._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseEdgeContainerRestTransport._BaseUpdateNodePool._get_query_params_json(transcoded_request) - - # Send the request - response = EdgeContainerRestTransport._UpdateNodePool._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_node_pool(resp) - return resp - - class _UpgradeCluster(_BaseEdgeContainerRestTransport._BaseUpgradeCluster, EdgeContainerRestStub): - def __hash__(self): - return hash("EdgeContainerRestTransport.UpgradeCluster") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: service.UpgradeClusterRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the upgrade cluster method over HTTP. - - Args: - request (~.service.UpgradeClusterRequest): - The request object. Upgrades a cluster. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options = _BaseEdgeContainerRestTransport._BaseUpgradeCluster._get_http_options() - request, metadata = self._interceptor.pre_upgrade_cluster(request, metadata) - transcoded_request = _BaseEdgeContainerRestTransport._BaseUpgradeCluster._get_transcoded_request(http_options, request) - - body = _BaseEdgeContainerRestTransport._BaseUpgradeCluster._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseEdgeContainerRestTransport._BaseUpgradeCluster._get_query_params_json(transcoded_request) - - # Send the request - response = EdgeContainerRestTransport._UpgradeCluster._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_upgrade_cluster(resp) - return resp - - @property - def create_cluster(self) -> Callable[ - [service.CreateClusterRequest], - 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._CreateCluster(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_node_pool(self) -> Callable[ - [service.CreateNodePoolRequest], - 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._CreateNodePool(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_vpn_connection(self) -> Callable[ - [service.CreateVpnConnectionRequest], - 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._CreateVpnConnection(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_cluster(self) -> Callable[ - [service.DeleteClusterRequest], - 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._DeleteCluster(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_node_pool(self) -> Callable[ - [service.DeleteNodePoolRequest], - 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._DeleteNodePool(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_vpn_connection(self) -> Callable[ - [service.DeleteVpnConnectionRequest], - 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._DeleteVpnConnection(self._session, self._host, self._interceptor) # type: ignore - - @property - def generate_access_token(self) -> Callable[ - [service.GenerateAccessTokenRequest], - service.GenerateAccessTokenResponse]: - # 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._GenerateAccessToken(self._session, self._host, self._interceptor) # type: ignore - - @property - def generate_offline_credential(self) -> Callable[ - [service.GenerateOfflineCredentialRequest], - service.GenerateOfflineCredentialResponse]: - # 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._GenerateOfflineCredential(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_cluster(self) -> Callable[ - [service.GetClusterRequest], - resources.Cluster]: - # 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._GetCluster(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_machine(self) -> Callable[ - [service.GetMachineRequest], - resources.Machine]: - # 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._GetMachine(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_node_pool(self) -> Callable[ - [service.GetNodePoolRequest], - resources.NodePool]: - # 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._GetNodePool(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_server_config(self) -> Callable[ - [service.GetServerConfigRequest], - resources.ServerConfig]: - # 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._GetServerConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_vpn_connection(self) -> Callable[ - [service.GetVpnConnectionRequest], - resources.VpnConnection]: - # 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._GetVpnConnection(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_clusters(self) -> Callable[ - [service.ListClustersRequest], - service.ListClustersResponse]: - # 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._ListClusters(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_machines(self) -> Callable[ - [service.ListMachinesRequest], - service.ListMachinesResponse]: - # 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._ListMachines(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_node_pools(self) -> Callable[ - [service.ListNodePoolsRequest], - service.ListNodePoolsResponse]: - # 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._ListNodePools(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_vpn_connections(self) -> Callable[ - [service.ListVpnConnectionsRequest], - service.ListVpnConnectionsResponse]: - # 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._ListVpnConnections(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_cluster(self) -> Callable[ - [service.UpdateClusterRequest], - 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._UpdateCluster(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_node_pool(self) -> Callable[ - [service.UpdateNodePoolRequest], - 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._UpdateNodePool(self._session, self._host, self._interceptor) # type: ignore - - @property - def upgrade_cluster(self) -> Callable[ - [service.UpgradeClusterRequest], - 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._UpgradeCluster(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_location(self): - return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore - - class _GetLocation(_BaseEdgeContainerRestTransport._BaseGetLocation, EdgeContainerRestStub): - def __hash__(self): - return hash("EdgeContainerRestTransport.GetLocation") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: locations_pb2.GetLocationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> locations_pb2.Location: - - r"""Call the get location method over HTTP. - - Args: - request (locations_pb2.GetLocationRequest): - The request object for GetLocation method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - locations_pb2.Location: Response from GetLocation method. - """ - - http_options = _BaseEdgeContainerRestTransport._BaseGetLocation._get_http_options() - request, metadata = self._interceptor.pre_get_location(request, metadata) - transcoded_request = _BaseEdgeContainerRestTransport._BaseGetLocation._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseEdgeContainerRestTransport._BaseGetLocation._get_query_params_json(transcoded_request) - - # Send the request - response = EdgeContainerRestTransport._GetLocation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - content = response.content.decode("utf-8") - resp = locations_pb2.Location() - resp = json_format.Parse(content, resp) - resp = self._interceptor.post_get_location(resp) - return resp - - @property - def list_locations(self): - return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore - - class _ListLocations(_BaseEdgeContainerRestTransport._BaseListLocations, EdgeContainerRestStub): - def __hash__(self): - return hash("EdgeContainerRestTransport.ListLocations") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: locations_pb2.ListLocationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> locations_pb2.ListLocationsResponse: - - r"""Call the list locations method over HTTP. - - Args: - request (locations_pb2.ListLocationsRequest): - The request object for ListLocations method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - locations_pb2.ListLocationsResponse: Response from ListLocations method. - """ - - http_options = _BaseEdgeContainerRestTransport._BaseListLocations._get_http_options() - request, metadata = self._interceptor.pre_list_locations(request, metadata) - transcoded_request = _BaseEdgeContainerRestTransport._BaseListLocations._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseEdgeContainerRestTransport._BaseListLocations._get_query_params_json(transcoded_request) - - # Send the request - response = EdgeContainerRestTransport._ListLocations._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - content = response.content.decode("utf-8") - resp = locations_pb2.ListLocationsResponse() - resp = json_format.Parse(content, resp) - resp = self._interceptor.post_list_locations(resp) - return resp - - @property - def cancel_operation(self): - return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore - - class _CancelOperation(_BaseEdgeContainerRestTransport._BaseCancelOperation, EdgeContainerRestStub): - def __hash__(self): - return hash("EdgeContainerRestTransport.CancelOperation") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: operations_pb2.CancelOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> None: - - r"""Call the cancel operation method over HTTP. - - Args: - request (operations_pb2.CancelOperationRequest): - The request object for CancelOperation method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - - http_options = _BaseEdgeContainerRestTransport._BaseCancelOperation._get_http_options() - request, metadata = self._interceptor.pre_cancel_operation(request, metadata) - transcoded_request = _BaseEdgeContainerRestTransport._BaseCancelOperation._get_transcoded_request(http_options, request) - - body = _BaseEdgeContainerRestTransport._BaseCancelOperation._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseEdgeContainerRestTransport._BaseCancelOperation._get_query_params_json(transcoded_request) - - # Send the request - response = EdgeContainerRestTransport._CancelOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - return self._interceptor.post_cancel_operation(None) - - @property - def delete_operation(self): - return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore - - class _DeleteOperation(_BaseEdgeContainerRestTransport._BaseDeleteOperation, EdgeContainerRestStub): - def __hash__(self): - return hash("EdgeContainerRestTransport.DeleteOperation") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: operations_pb2.DeleteOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> None: - - r"""Call the delete operation method over HTTP. - - Args: - request (operations_pb2.DeleteOperationRequest): - The request object for DeleteOperation method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - - http_options = _BaseEdgeContainerRestTransport._BaseDeleteOperation._get_http_options() - request, metadata = self._interceptor.pre_delete_operation(request, metadata) - transcoded_request = _BaseEdgeContainerRestTransport._BaseDeleteOperation._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseEdgeContainerRestTransport._BaseDeleteOperation._get_query_params_json(transcoded_request) - - # Send the request - response = EdgeContainerRestTransport._DeleteOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - return self._interceptor.post_delete_operation(None) - - @property - def get_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - - class _GetOperation(_BaseEdgeContainerRestTransport._BaseGetOperation, EdgeContainerRestStub): - def __hash__(self): - return hash("EdgeContainerRestTransport.GetOperation") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: operations_pb2.GetOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - - r"""Call the get operation method over HTTP. - - Args: - request (operations_pb2.GetOperationRequest): - The request object for GetOperation method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - operations_pb2.Operation: Response from GetOperation method. - """ - - http_options = _BaseEdgeContainerRestTransport._BaseGetOperation._get_http_options() - request, metadata = self._interceptor.pre_get_operation(request, metadata) - transcoded_request = _BaseEdgeContainerRestTransport._BaseGetOperation._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseEdgeContainerRestTransport._BaseGetOperation._get_query_params_json(transcoded_request) - - # Send the request - response = EdgeContainerRestTransport._GetOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - content = response.content.decode("utf-8") - resp = operations_pb2.Operation() - resp = json_format.Parse(content, resp) - resp = self._interceptor.post_get_operation(resp) - return resp - - @property - def list_operations(self): - return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - - class _ListOperations(_BaseEdgeContainerRestTransport._BaseListOperations, EdgeContainerRestStub): - def __hash__(self): - return hash("EdgeContainerRestTransport.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, str]]=(), - ) -> operations_pb2.ListOperationsResponse: - - r"""Call the list operations method over HTTP. - - Args: - request (operations_pb2.ListOperationsRequest): - The request object for ListOperations method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - operations_pb2.ListOperationsResponse: Response from ListOperations method. - """ - - http_options = _BaseEdgeContainerRestTransport._BaseListOperations._get_http_options() - request, metadata = self._interceptor.pre_list_operations(request, metadata) - transcoded_request = _BaseEdgeContainerRestTransport._BaseListOperations._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseEdgeContainerRestTransport._BaseListOperations._get_query_params_json(transcoded_request) - - # Send the request - response = EdgeContainerRestTransport._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) - return resp - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'EdgeContainerRestTransport', -) diff --git a/owl-bot-staging/google-cloud-edgecontainer/v1/google/cloud/edgecontainer_v1/services/edge_container/transports/rest_base.py b/owl-bot-staging/google-cloud-edgecontainer/v1/google/cloud/edgecontainer_v1/services/edge_container/transports/rest_base.py deleted file mode 100644 index bd91d3541abe..000000000000 --- a/owl-bot-staging/google-cloud-edgecontainer/v1/google/cloud/edgecontainer_v1/services/edge_container/transports/rest_base.py +++ /dev/null @@ -1,1033 +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.cloud.location import locations_pb2 # type: ignore -from .base import EdgeContainerTransport, DEFAULT_CLIENT_INFO - -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union - - -from google.cloud.edgecontainer_v1.types import resources -from google.cloud.edgecontainer_v1.types import service -from google.longrunning import operations_pb2 # type: ignore - - -class _BaseEdgeContainerRestTransport(EdgeContainerTransport): - """Base REST backend transport for EdgeContainer. - - 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 = 'edgecontainer.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: 'edgecontainer.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 _BaseCreateCluster: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "clusterId" : "", } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/locations/*}/clusters', - 'body': 'cluster', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = service.CreateClusterRequest.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(_BaseEdgeContainerRestTransport._BaseCreateCluster._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseCreateNodePool: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "nodePoolId" : "", } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/locations/*/clusters/*}/nodePools', - 'body': 'node_pool', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = service.CreateNodePoolRequest.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(_BaseEdgeContainerRestTransport._BaseCreateNodePool._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseCreateVpnConnection: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "vpnConnectionId" : "", } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/locations/*}/vpnConnections', - 'body': 'vpn_connection', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = service.CreateVpnConnectionRequest.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(_BaseEdgeContainerRestTransport._BaseCreateVpnConnection._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseDeleteCluster: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/clusters/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = service.DeleteClusterRequest.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(_BaseEdgeContainerRestTransport._BaseDeleteCluster._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseDeleteNodePool: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/clusters/*/nodePools/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = service.DeleteNodePoolRequest.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(_BaseEdgeContainerRestTransport._BaseDeleteNodePool._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseDeleteVpnConnection: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/vpnConnections/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = service.DeleteVpnConnectionRequest.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(_BaseEdgeContainerRestTransport._BaseDeleteVpnConnection._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGenerateAccessToken: - 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/{cluster=projects/*/locations/*/clusters/*}:generateAccessToken', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = service.GenerateAccessTokenRequest.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(_BaseEdgeContainerRestTransport._BaseGenerateAccessToken._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGenerateOfflineCredential: - 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/{cluster=projects/*/locations/*/clusters/*}:generateOfflineCredential', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = service.GenerateOfflineCredentialRequest.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(_BaseEdgeContainerRestTransport._BaseGenerateOfflineCredential._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetCluster: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/clusters/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = service.GetClusterRequest.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(_BaseEdgeContainerRestTransport._BaseGetCluster._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetMachine: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/machines/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = service.GetMachineRequest.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(_BaseEdgeContainerRestTransport._BaseGetMachine._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetNodePool: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/clusters/*/nodePools/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = service.GetNodePoolRequest.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(_BaseEdgeContainerRestTransport._BaseGetNodePool._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetServerConfig: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*}/serverConfig', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = service.GetServerConfigRequest.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(_BaseEdgeContainerRestTransport._BaseGetServerConfig._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetVpnConnection: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/vpnConnections/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = service.GetVpnConnectionRequest.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(_BaseEdgeContainerRestTransport._BaseGetVpnConnection._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseListClusters: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/locations/*}/clusters', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = service.ListClustersRequest.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(_BaseEdgeContainerRestTransport._BaseListClusters._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseListMachines: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/locations/*}/machines', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = service.ListMachinesRequest.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(_BaseEdgeContainerRestTransport._BaseListMachines._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseListNodePools: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/locations/*/clusters/*}/nodePools', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = service.ListNodePoolsRequest.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(_BaseEdgeContainerRestTransport._BaseListNodePools._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseListVpnConnections: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/locations/*}/vpnConnections', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = service.ListVpnConnectionsRequest.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(_BaseEdgeContainerRestTransport._BaseListVpnConnections._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseUpdateCluster: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1/{cluster.name=projects/*/locations/*/clusters/*}', - 'body': 'cluster', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = service.UpdateClusterRequest.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["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseUpdateNodePool: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1/{node_pool.name=projects/*/locations/*/clusters/*/nodePools/*}', - 'body': 'node_pool', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = service.UpdateNodePoolRequest.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["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseUpgradeCluster: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{name=projects/*/locations/*/clusters/*}:upgrade', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = service.UpgradeClusterRequest.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(_BaseEdgeContainerRestTransport._BaseUpgradeCluster._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetLocation: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - return query_params - - class _BaseListLocations: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*}/locations', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - return query_params - - class _BaseCancelOperation: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}:cancel', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - body = json.dumps(transcoded_request['body']) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - return query_params - - class _BaseDeleteOperation: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - return query_params - - class _BaseGetOperation: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - return query_params - - class _BaseListOperations: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*}/operations', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - return query_params - - -__all__=( - '_BaseEdgeContainerRestTransport', -) diff --git a/owl-bot-staging/google-cloud-edgecontainer/v1/google/cloud/edgecontainer_v1/types/__init__.py b/owl-bot-staging/google-cloud-edgecontainer/v1/google/cloud/edgecontainer_v1/types/__init__.py deleted file mode 100644 index 86539c77c4cb..000000000000 --- a/owl-bot-staging/google-cloud-edgecontainer/v1/google/cloud/edgecontainer_v1/types/__init__.py +++ /dev/null @@ -1,114 +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 ( - Authorization, - ChannelConfig, - Cluster, - ClusterNetworking, - ClusterUser, - Fleet, - LocationMetadata, - Machine, - MaintenancePolicy, - MaintenanceWindow, - NodePool, - Quota, - RecurringTimeWindow, - ServerConfig, - TimeWindow, - Version, - VpnConnection, - ZoneMetadata, - KmsKeyState, -) -from .service import ( - CreateClusterRequest, - CreateNodePoolRequest, - CreateVpnConnectionRequest, - DeleteClusterRequest, - DeleteNodePoolRequest, - DeleteVpnConnectionRequest, - GenerateAccessTokenRequest, - GenerateAccessTokenResponse, - GenerateOfflineCredentialRequest, - GenerateOfflineCredentialResponse, - GetClusterRequest, - GetMachineRequest, - GetNodePoolRequest, - GetServerConfigRequest, - GetVpnConnectionRequest, - ListClustersRequest, - ListClustersResponse, - ListMachinesRequest, - ListMachinesResponse, - ListNodePoolsRequest, - ListNodePoolsResponse, - ListVpnConnectionsRequest, - ListVpnConnectionsResponse, - OperationMetadata, - UpdateClusterRequest, - UpdateNodePoolRequest, - UpgradeClusterRequest, -) - -__all__ = ( - 'Authorization', - 'ChannelConfig', - 'Cluster', - 'ClusterNetworking', - 'ClusterUser', - 'Fleet', - 'LocationMetadata', - 'Machine', - 'MaintenancePolicy', - 'MaintenanceWindow', - 'NodePool', - 'Quota', - 'RecurringTimeWindow', - 'ServerConfig', - 'TimeWindow', - 'Version', - 'VpnConnection', - 'ZoneMetadata', - 'KmsKeyState', - 'CreateClusterRequest', - 'CreateNodePoolRequest', - 'CreateVpnConnectionRequest', - 'DeleteClusterRequest', - 'DeleteNodePoolRequest', - 'DeleteVpnConnectionRequest', - 'GenerateAccessTokenRequest', - 'GenerateAccessTokenResponse', - 'GenerateOfflineCredentialRequest', - 'GenerateOfflineCredentialResponse', - 'GetClusterRequest', - 'GetMachineRequest', - 'GetNodePoolRequest', - 'GetServerConfigRequest', - 'GetVpnConnectionRequest', - 'ListClustersRequest', - 'ListClustersResponse', - 'ListMachinesRequest', - 'ListMachinesResponse', - 'ListNodePoolsRequest', - 'ListNodePoolsResponse', - 'ListVpnConnectionsRequest', - 'ListVpnConnectionsResponse', - 'OperationMetadata', - 'UpdateClusterRequest', - 'UpdateNodePoolRequest', - 'UpgradeClusterRequest', -) diff --git a/owl-bot-staging/google-cloud-edgecontainer/v1/google/cloud/edgecontainer_v1/types/resources.py b/owl-bot-staging/google-cloud-edgecontainer/v1/google/cloud/edgecontainer_v1/types/resources.py deleted file mode 100644 index d96c16bc3645..000000000000 --- a/owl-bot-staging/google-cloud-edgecontainer/v1/google/cloud/edgecontainer_v1/types/resources.py +++ /dev/null @@ -1,1422 +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.protobuf import duration_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.edgecontainer.v1', - manifest={ - 'KmsKeyState', - 'Cluster', - 'ClusterNetworking', - 'Fleet', - 'ClusterUser', - 'Authorization', - 'NodePool', - 'Machine', - 'VpnConnection', - 'LocationMetadata', - 'ZoneMetadata', - 'Quota', - 'MaintenancePolicy', - 'MaintenanceWindow', - 'RecurringTimeWindow', - 'TimeWindow', - 'ServerConfig', - 'ChannelConfig', - 'Version', - }, -) - - -class KmsKeyState(proto.Enum): - r"""Represents the accessibility state of a customer-managed KMS - key used for CMEK integration. - - Values: - KMS_KEY_STATE_UNSPECIFIED (0): - Unspecified. - KMS_KEY_STATE_KEY_AVAILABLE (1): - The key is available for use, and dependent - resources should be accessible. - KMS_KEY_STATE_KEY_UNAVAILABLE (2): - The key is unavailable for an unspecified - reason. Dependent resources may be inaccessible. - """ - KMS_KEY_STATE_UNSPECIFIED = 0 - KMS_KEY_STATE_KEY_AVAILABLE = 1 - KMS_KEY_STATE_KEY_UNAVAILABLE = 2 - - -class Cluster(proto.Message): - r"""A Google Distributed Cloud Edge Kubernetes cluster. - - Attributes: - name (str): - Required. The resource name of the cluster. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time when the cluster was - created. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time when the cluster was - last updated. - labels (MutableMapping[str, str]): - Labels associated with this resource. - fleet (google.cloud.edgecontainer_v1.types.Fleet): - Required. Fleet configuration. - networking (google.cloud.edgecontainer_v1.types.ClusterNetworking): - Required. Cluster-wide networking - configuration. - authorization (google.cloud.edgecontainer_v1.types.Authorization): - Required. Immutable. RBAC policy that will be - applied and managed by GEC. - default_max_pods_per_node (int): - Optional. The default maximum number of pods - per node used if a maximum value is not - specified explicitly for a node pool in this - cluster. If unspecified, the Kubernetes default - value will be used. - endpoint (str): - Output only. The IP address of the Kubernetes - API server. - port (int): - Output only. The port number of the - Kubernetes API server. - cluster_ca_certificate (str): - Output only. The PEM-encoded public - certificate of the cluster's CA. - maintenance_policy (google.cloud.edgecontainer_v1.types.MaintenancePolicy): - Optional. Cluster-wide maintenance policy - configuration. - control_plane_version (str): - Output only. The control plane release - version - node_version (str): - Output only. The lowest release version among - all worker nodes. This field can be empty if the - cluster does not have any worker nodes. - control_plane (google.cloud.edgecontainer_v1.types.Cluster.ControlPlane): - Optional. The configuration of the cluster - control plane. - system_addons_config (google.cloud.edgecontainer_v1.types.Cluster.SystemAddonsConfig): - Optional. The configuration of the system - add-ons. - external_load_balancer_ipv4_address_pools (MutableSequence[str]): - Optional. IPv4 address pools for cluster data - plane external load balancing. - control_plane_encryption (google.cloud.edgecontainer_v1.types.Cluster.ControlPlaneEncryption): - Optional. Remote control plane disk - encryption options. This field is only used when - enabling CMEK support. - status (google.cloud.edgecontainer_v1.types.Cluster.Status): - Output only. The current status of the - cluster. - maintenance_events (MutableSequence[google.cloud.edgecontainer_v1.types.Cluster.MaintenanceEvent]): - Output only. All the maintenance events - scheduled for the cluster, including the ones - ongoing, planned for the future and done in the - past (up to 90 days). - target_version (str): - Optional. The target cluster version. For - example: "1.5.0". - release_channel (google.cloud.edgecontainer_v1.types.Cluster.ReleaseChannel): - Optional. The release channel a cluster is - subscribed to. - survivability_config (google.cloud.edgecontainer_v1.types.Cluster.SurvivabilityConfig): - Optional. Configuration of the cluster - survivability, e.g., for the case when network - connectivity is lost. Note: This only applies to - local control plane clusters. - external_load_balancer_ipv6_address_pools (MutableSequence[str]): - Optional. IPv6 address pools for cluster data - plane external load balancing. - """ - class Status(proto.Enum): - r"""Indicates the status of the cluster. - - Values: - STATUS_UNSPECIFIED (0): - Status unknown. - PROVISIONING (1): - The cluster is being created. - RUNNING (2): - The cluster is created and fully usable. - DELETING (3): - The cluster is being deleted. - ERROR (4): - The status indicates that some errors - occurred while reconciling/deleting the cluster. - RECONCILING (5): - The cluster is undergoing some work such as - version upgrades, etc. - """ - STATUS_UNSPECIFIED = 0 - PROVISIONING = 1 - RUNNING = 2 - DELETING = 3 - ERROR = 4 - RECONCILING = 5 - - class ReleaseChannel(proto.Enum): - r"""The release channel a cluster is subscribed to. - - Values: - RELEASE_CHANNEL_UNSPECIFIED (0): - Unspecified release channel. This will - default to the REGULAR channel. - NONE (1): - No release channel. - REGULAR (2): - Regular release channel. - """ - RELEASE_CHANNEL_UNSPECIFIED = 0 - NONE = 1 - REGULAR = 2 - - class ControlPlane(proto.Message): - r"""Configuration of the cluster control plane. - - 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: - remote (google.cloud.edgecontainer_v1.types.Cluster.ControlPlane.Remote): - Remote control plane configuration. - - This field is a member of `oneof`_ ``config``. - local (google.cloud.edgecontainer_v1.types.Cluster.ControlPlane.Local): - Local control plane configuration. - - Warning: Local control plane clusters must be - created in their own project. Local control - plane clusters cannot coexist in the same - project with any other type of clusters, - including non-GDCE clusters. Mixing local - control plane GDCE clusters with any other type - of clusters in the same project can result in - data loss. - - This field is a member of `oneof`_ ``config``. - """ - class SharedDeploymentPolicy(proto.Enum): - r"""Represents the policy configuration about how user - applications are deployed. - - Values: - SHARED_DEPLOYMENT_POLICY_UNSPECIFIED (0): - Unspecified. - ALLOWED (1): - User applications can be deployed both on - control plane and worker nodes. - DISALLOWED (2): - User applications can not be deployed on - control plane nodes and can only be deployed on - worker nodes. - """ - SHARED_DEPLOYMENT_POLICY_UNSPECIFIED = 0 - ALLOWED = 1 - DISALLOWED = 2 - - class Remote(proto.Message): - r"""Configuration specific to clusters with a control plane - hosted remotely. - - """ - - class Local(proto.Message): - r"""Configuration specific to clusters with a control plane - hosted locally. - Warning: Local control plane clusters must be created in their - own project. Local control plane clusters cannot coexist in the - same project with any other type of clusters, including non-GDCE - clusters. Mixing local control plane GDCE clusters with any - other type of clusters in the same project can result in data - loss. - - Attributes: - node_location (str): - Name of the Google Distributed Cloud Edge zones where this - node pool will be created. For example: - ``us-central1-edge-customer-a``. - node_count (int): - The number of nodes to serve as replicas of - the Control Plane. - machine_filter (str): - Only machines matching this filter will be allowed to host - control plane nodes. The filtering language accepts strings - like "name=", and is documented here: - `AIP-160 `__. - shared_deployment_policy (google.cloud.edgecontainer_v1.types.Cluster.ControlPlane.SharedDeploymentPolicy): - Policy configuration about how user - applications are deployed. - """ - - node_location: str = proto.Field( - proto.STRING, - number=1, - ) - node_count: int = proto.Field( - proto.INT32, - number=2, - ) - machine_filter: str = proto.Field( - proto.STRING, - number=3, - ) - shared_deployment_policy: 'Cluster.ControlPlane.SharedDeploymentPolicy' = proto.Field( - proto.ENUM, - number=4, - enum='Cluster.ControlPlane.SharedDeploymentPolicy', - ) - - remote: 'Cluster.ControlPlane.Remote' = proto.Field( - proto.MESSAGE, - number=1, - oneof='config', - message='Cluster.ControlPlane.Remote', - ) - local: 'Cluster.ControlPlane.Local' = proto.Field( - proto.MESSAGE, - number=2, - oneof='config', - message='Cluster.ControlPlane.Local', - ) - - class SystemAddonsConfig(proto.Message): - r"""Config that customers are allowed to define for GDCE system - add-ons. - - Attributes: - ingress (google.cloud.edgecontainer_v1.types.Cluster.SystemAddonsConfig.Ingress): - Optional. Config for Ingress. - """ - - class Ingress(proto.Message): - r"""Config for the Ingress add-on which allows customers to - create an Ingress object to manage external access to the - servers in a cluster. The add-on consists of istiod and - istio-ingress. - - Attributes: - disabled (bool): - Optional. Whether Ingress is disabled. - ipv4_vip (str): - Optional. Ingress VIP. - """ - - disabled: bool = proto.Field( - proto.BOOL, - number=1, - ) - ipv4_vip: str = proto.Field( - proto.STRING, - number=2, - ) - - ingress: 'Cluster.SystemAddonsConfig.Ingress' = proto.Field( - proto.MESSAGE, - number=1, - message='Cluster.SystemAddonsConfig.Ingress', - ) - - class ControlPlaneEncryption(proto.Message): - r"""Configuration for Customer-managed KMS key support for remote - control plane cluster disk encryption. - - Attributes: - kms_key (str): - Immutable. The Cloud KMS CryptoKey e.g. - projects/{project}/locations/{location}/keyRings/{keyRing}/cryptoKeys/{cryptoKey} - to use for protecting control plane disks. If - not specified, a Google-managed key will be used - instead. - kms_key_active_version (str): - Output only. The Cloud KMS CryptoKeyVersion currently in use - for protecting control plane disks. Only applicable if - kms_key is set. - kms_key_state (google.cloud.edgecontainer_v1.types.KmsKeyState): - Output only. Availability of the Cloud KMS CryptoKey. If not - ``KEY_AVAILABLE``, then nodes may go offline as they cannot - access their local data. This can be caused by a lack of - permissions to use the key, or if the key is disabled or - deleted. - kms_status (google.rpc.status_pb2.Status): - Output only. Error status returned by Cloud KMS when using - this key. This field may be populated only if - ``kms_key_state`` is not ``KMS_KEY_STATE_KEY_AVAILABLE``. If - populated, this field contains the error status reported by - Cloud KMS. - """ - - kms_key: str = proto.Field( - proto.STRING, - number=1, - ) - kms_key_active_version: str = proto.Field( - proto.STRING, - number=2, - ) - kms_key_state: 'KmsKeyState' = proto.Field( - proto.ENUM, - number=3, - enum='KmsKeyState', - ) - kms_status: status_pb2.Status = proto.Field( - proto.MESSAGE, - number=4, - message=status_pb2.Status, - ) - - class MaintenanceEvent(proto.Message): - r"""A Maintenance Event is an operation that could cause - temporary disruptions to the cluster workloads, including - Google-driven or user-initiated cluster upgrades, user-initiated - cluster configuration changes that require restarting nodes, - etc. - - Attributes: - uuid (str): - Output only. UUID of the maintenance event. - target_version (str): - Output only. The target version of the - cluster. - operation (str): - Output only. The operation for running the maintenance - event. Specified in the format - projects/\ */locations/*/operations/*. If the maintenance - event is split into multiple operations (e.g. due to - maintenance windows), the latest one is recorded. - type_ (google.cloud.edgecontainer_v1.types.Cluster.MaintenanceEvent.Type): - Output only. The type of the maintenance - event. - schedule (google.cloud.edgecontainer_v1.types.Cluster.MaintenanceEvent.Schedule): - Output only. The schedule of the maintenance - event. - state (google.cloud.edgecontainer_v1.types.Cluster.MaintenanceEvent.State): - Output only. The state of the maintenance - event. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time when the maintenance - event request was created. - start_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time when the maintenance - event started. - end_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time when the maintenance event ended, - either successfully or not. If the maintenance event is - split into multiple maintenance windows, end_time is only - updated when the whole flow ends. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time when the maintenance - event message was updated. - """ - class Type(proto.Enum): - r"""Indicates the maintenance event type. - - Values: - TYPE_UNSPECIFIED (0): - Unspecified. - USER_INITIATED_UPGRADE (1): - Upgrade initiated by users. - GOOGLE_DRIVEN_UPGRADE (2): - Upgrade driven by Google. - """ - TYPE_UNSPECIFIED = 0 - USER_INITIATED_UPGRADE = 1 - GOOGLE_DRIVEN_UPGRADE = 2 - - class Schedule(proto.Enum): - r"""Indicates when the maintenance event should be performed. - - Values: - SCHEDULE_UNSPECIFIED (0): - Unspecified. - IMMEDIATELY (1): - Immediately after receiving the request. - """ - SCHEDULE_UNSPECIFIED = 0 - IMMEDIATELY = 1 - - class State(proto.Enum): - r"""Indicates the maintenance event state. - - Values: - STATE_UNSPECIFIED (0): - Unspecified. - RECONCILING (1): - The maintenance event is ongoing. The cluster - might be unusable. - SUCCEEDED (2): - The maintenance event succeeded. - FAILED (3): - The maintenance event failed. - """ - STATE_UNSPECIFIED = 0 - RECONCILING = 1 - SUCCEEDED = 2 - FAILED = 3 - - uuid: str = proto.Field( - proto.STRING, - number=1, - ) - target_version: str = proto.Field( - proto.STRING, - number=2, - ) - operation: str = proto.Field( - proto.STRING, - number=3, - ) - type_: 'Cluster.MaintenanceEvent.Type' = proto.Field( - proto.ENUM, - number=4, - enum='Cluster.MaintenanceEvent.Type', - ) - schedule: 'Cluster.MaintenanceEvent.Schedule' = proto.Field( - proto.ENUM, - number=5, - enum='Cluster.MaintenanceEvent.Schedule', - ) - state: 'Cluster.MaintenanceEvent.State' = proto.Field( - proto.ENUM, - number=6, - enum='Cluster.MaintenanceEvent.State', - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=7, - message=timestamp_pb2.Timestamp, - ) - start_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=8, - message=timestamp_pb2.Timestamp, - ) - end_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=9, - message=timestamp_pb2.Timestamp, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=10, - message=timestamp_pb2.Timestamp, - ) - - class SurvivabilityConfig(proto.Message): - r"""Configuration of the cluster survivability, e.g., for the - case when network connectivity is lost. - - Attributes: - offline_reboot_ttl (google.protobuf.duration_pb2.Duration): - Optional. Time period that allows the cluster - nodes to be rebooted and become functional - without network connectivity to Google. The - default 0 means not allowed. The maximum is 7 - days. - """ - - offline_reboot_ttl: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=1, - message=duration_pb2.Duration, - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - labels: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=4, - ) - fleet: 'Fleet' = proto.Field( - proto.MESSAGE, - number=11, - message='Fleet', - ) - networking: 'ClusterNetworking' = proto.Field( - proto.MESSAGE, - number=7, - message='ClusterNetworking', - ) - authorization: 'Authorization' = proto.Field( - proto.MESSAGE, - number=9, - message='Authorization', - ) - default_max_pods_per_node: int = proto.Field( - proto.INT32, - number=8, - ) - endpoint: str = proto.Field( - proto.STRING, - number=6, - ) - port: int = proto.Field( - proto.INT32, - number=19, - ) - cluster_ca_certificate: str = proto.Field( - proto.STRING, - number=10, - ) - maintenance_policy: 'MaintenancePolicy' = proto.Field( - proto.MESSAGE, - number=12, - message='MaintenancePolicy', - ) - control_plane_version: str = proto.Field( - proto.STRING, - number=13, - ) - node_version: str = proto.Field( - proto.STRING, - number=14, - ) - control_plane: ControlPlane = proto.Field( - proto.MESSAGE, - number=15, - message=ControlPlane, - ) - system_addons_config: SystemAddonsConfig = proto.Field( - proto.MESSAGE, - number=16, - message=SystemAddonsConfig, - ) - external_load_balancer_ipv4_address_pools: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=17, - ) - control_plane_encryption: ControlPlaneEncryption = proto.Field( - proto.MESSAGE, - number=18, - message=ControlPlaneEncryption, - ) - status: Status = proto.Field( - proto.ENUM, - number=20, - enum=Status, - ) - maintenance_events: MutableSequence[MaintenanceEvent] = proto.RepeatedField( - proto.MESSAGE, - number=21, - message=MaintenanceEvent, - ) - target_version: str = proto.Field( - proto.STRING, - number=22, - ) - release_channel: ReleaseChannel = proto.Field( - proto.ENUM, - number=23, - enum=ReleaseChannel, - ) - survivability_config: SurvivabilityConfig = proto.Field( - proto.MESSAGE, - number=24, - message=SurvivabilityConfig, - ) - external_load_balancer_ipv6_address_pools: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=25, - ) - - -class ClusterNetworking(proto.Message): - r"""Cluster-wide networking configuration. - - Attributes: - cluster_ipv4_cidr_blocks (MutableSequence[str]): - Required. All pods in the cluster are - assigned an RFC1918 IPv4 address from these - blocks. Only a single block is supported. This - field cannot be changed after creation. - services_ipv4_cidr_blocks (MutableSequence[str]): - Required. All services in the cluster are - assigned an RFC1918 IPv4 address from these - blocks. Only a single block is supported. This - field cannot be changed after creation. - """ - - cluster_ipv4_cidr_blocks: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=1, - ) - services_ipv4_cidr_blocks: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=2, - ) - - -class Fleet(proto.Message): - r"""Fleet related configuration. - - Fleets are a Google Cloud concept for logically organizing - clusters, letting you use and manage multi-cluster capabilities - and apply consistent policies across your systems. - - Attributes: - project (str): - Required. The name of the Fleet host project where this - cluster will be registered. - - Project names are formatted as - ``projects/``. - membership (str): - Output only. The name of the managed Hub Membership resource - associated to this cluster. - - Membership names are formatted as - ``projects//locations/global/membership/``. - """ - - project: str = proto.Field( - proto.STRING, - number=1, - ) - membership: str = proto.Field( - proto.STRING, - number=2, - ) - - -class ClusterUser(proto.Message): - r"""A user principal for an RBAC policy. - - Attributes: - username (str): - Required. An active Google username. - """ - - username: str = proto.Field( - proto.STRING, - number=1, - ) - - -class Authorization(proto.Message): - r"""RBAC policy that will be applied and managed by GEC. - - Attributes: - admin_users (google.cloud.edgecontainer_v1.types.ClusterUser): - Required. User that will be granted the - cluster-admin role on the cluster, providing - full access to the cluster. Currently, this is a - singular field, but will be expanded to allow - multiple admins in the future. - """ - - admin_users: 'ClusterUser' = proto.Field( - proto.MESSAGE, - number=1, - message='ClusterUser', - ) - - -class NodePool(proto.Message): - r"""A set of Kubernetes nodes in a cluster with common - configuration and specification. - - Attributes: - name (str): - Required. The resource name of the node pool. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time when the node pool was - created. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time when the node pool was - last updated. - labels (MutableMapping[str, str]): - Labels associated with this resource. - node_location (str): - Name of the Google Distributed Cloud Edge zone where this - node pool will be created. For example: - ``us-central1-edge-customer-a``. - node_count (int): - Required. The number of nodes in the pool. - machine_filter (str): - Only machines matching this filter will be allowed to join - the node pool. The filtering language accepts strings like - "name=", and is documented in more detail in - `AIP-160 `__. - local_disk_encryption (google.cloud.edgecontainer_v1.types.NodePool.LocalDiskEncryption): - Optional. Local disk encryption options. This - field is only used when enabling CMEK support. - node_version (str): - Output only. The lowest release version among - all worker nodes. - node_config (google.cloud.edgecontainer_v1.types.NodePool.NodeConfig): - Optional. Configuration for each node in the - NodePool - """ - - class LocalDiskEncryption(proto.Message): - r"""Configuration for CMEK support for edge machine local disk - encryption. - - Attributes: - kms_key (str): - Immutable. The Cloud KMS CryptoKey e.g. - projects/{project}/locations/{location}/keyRings/{keyRing}/cryptoKeys/{cryptoKey} - to use for protecting node local disks. If not - specified, a Google-managed key will be used - instead. - kms_key_active_version (str): - Output only. The Cloud KMS CryptoKeyVersion currently in use - for protecting node local disks. Only applicable if kms_key - is set. - kms_key_state (google.cloud.edgecontainer_v1.types.KmsKeyState): - Output only. Availability of the Cloud KMS CryptoKey. If not - ``KEY_AVAILABLE``, then nodes may go offline as they cannot - access their local data. This can be caused by a lack of - permissions to use the key, or if the key is disabled or - deleted. - kms_status (google.rpc.status_pb2.Status): - Output only. Error status returned by Cloud KMS when using - this key. This field may be populated only if - ``kms_key_state`` is not ``KMS_KEY_STATE_KEY_AVAILABLE``. If - populated, this field contains the error status reported by - Cloud KMS. - """ - - kms_key: str = proto.Field( - proto.STRING, - number=1, - ) - kms_key_active_version: str = proto.Field( - proto.STRING, - number=2, - ) - kms_key_state: 'KmsKeyState' = proto.Field( - proto.ENUM, - number=3, - enum='KmsKeyState', - ) - kms_status: status_pb2.Status = proto.Field( - proto.MESSAGE, - number=4, - message=status_pb2.Status, - ) - - class NodeConfig(proto.Message): - r"""Configuration for each node in the NodePool - - Attributes: - labels (MutableMapping[str, str]): - Optional. The Kubernetes node labels - """ - - labels: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=1, - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - labels: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=4, - ) - node_location: str = proto.Field( - proto.STRING, - number=8, - ) - node_count: int = proto.Field( - proto.INT32, - number=6, - ) - machine_filter: str = proto.Field( - proto.STRING, - number=7, - ) - local_disk_encryption: LocalDiskEncryption = proto.Field( - proto.MESSAGE, - number=9, - message=LocalDiskEncryption, - ) - node_version: str = proto.Field( - proto.STRING, - number=10, - ) - node_config: NodeConfig = proto.Field( - proto.MESSAGE, - number=11, - message=NodeConfig, - ) - - -class Machine(proto.Message): - r"""A Google Distributed Cloud Edge machine capable of acting as - a Kubernetes node. - - Attributes: - name (str): - Required. The resource name of the machine. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time when the node pool was - created. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time when the node pool was - last updated. - labels (MutableMapping[str, str]): - Labels associated with this resource. - hosted_node (str): - Canonical resource name of the node that this machine is - responsible for hosting e.g. - projects/{project}/locations/{location}/clusters/{cluster_id}/nodePools/{pool_id}/{node}, - Or empty if the machine is not assigned to assume the role - of a node. - - For control plane nodes hosted on edge machines, this will - return the following format: - "projects/{project}/locations/{location}/clusters/{cluster_id}/controlPlaneNodes/{node}". - zone (str): - The Google Distributed Cloud Edge zone of - this machine. - version (str): - Output only. The software version of the - machine. - disabled (bool): - Output only. Whether the machine is disabled. - If disabled, the machine is unable to enter - service. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - labels: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=4, - ) - hosted_node: str = proto.Field( - proto.STRING, - number=5, - ) - zone: str = proto.Field( - proto.STRING, - number=6, - ) - version: str = proto.Field( - proto.STRING, - number=7, - ) - disabled: bool = proto.Field( - proto.BOOL, - number=8, - ) - - -class VpnConnection(proto.Message): - r"""A VPN connection . - - Attributes: - name (str): - Required. The resource name of VPN connection - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time when the VPN connection - was created. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time when the VPN connection - was last updated. - labels (MutableMapping[str, str]): - Labels associated with this resource. - nat_gateway_ip (str): - NAT gateway IP, or WAN IP address. If a - customer has multiple NAT IPs, the customer - needs to configure NAT such that only one - external IP maps to the GMEC Anthos cluster. - This is empty if NAT is not used. - bgp_routing_mode (google.cloud.edgecontainer_v1.types.VpnConnection.BgpRoutingMode): - Dynamic routing mode of the VPC network, ``regional`` or - ``global``. - cluster (str): - The canonical Cluster name to connect to. It - is in the form of - projects/{project}/locations/{location}/clusters/{cluster}. - vpc (str): - The network ID of VPC to connect to. - vpc_project (google.cloud.edgecontainer_v1.types.VpnConnection.VpcProject): - Optional. Project detail of the VPC network. - Required if VPC is in a different project than - the cluster project. - enable_high_availability (bool): - Whether this VPN connection has HA enabled on - cluster side. If enabled, when creating VPN - connection we will attempt to use 2 ANG floating - IPs. - router (str): - Optional. The VPN connection Cloud Router - name. - details (google.cloud.edgecontainer_v1.types.VpnConnection.Details): - Output only. The created connection details. - """ - class BgpRoutingMode(proto.Enum): - r"""Routing mode. - - Values: - BGP_ROUTING_MODE_UNSPECIFIED (0): - Unknown. - REGIONAL (1): - Regional mode. - GLOBAL (2): - Global mode. - """ - BGP_ROUTING_MODE_UNSPECIFIED = 0 - REGIONAL = 1 - GLOBAL = 2 - - class VpcProject(proto.Message): - r"""Project detail of the VPC network. - - Attributes: - project_id (str): - The project of the VPC to connect to. If not - specified, it is the same as the cluster - project. - service_account (str): - Optional. The service account in the VPC project configured - by user. It is used to create/delete Cloud Router and Cloud - HA VPNs for VPN connection. If this SA is changed - during/after a VPN connection is created, you need to remove - the Cloud Router and Cloud VPN resources in \|project_id|. - It is in the form of - service-{project_number}@gcp-sa-edgecontainer.iam.gserviceaccount.com. - """ - - project_id: str = proto.Field( - proto.STRING, - number=1, - ) - service_account: str = proto.Field( - proto.STRING, - number=2, - ) - - class Details(proto.Message): - r"""The created connection details. - - Attributes: - state (google.cloud.edgecontainer_v1.types.VpnConnection.Details.State): - The state of this connection. - error (str): - The error message. This is only populated - when state=ERROR. - cloud_router (google.cloud.edgecontainer_v1.types.VpnConnection.Details.CloudRouter): - The Cloud Router info. - cloud_vpns (MutableSequence[google.cloud.edgecontainer_v1.types.VpnConnection.Details.CloudVpn]): - Each connection has multiple Cloud VPN - gateways. - """ - class State(proto.Enum): - r"""The current connection state. - - Values: - STATE_UNSPECIFIED (0): - Unknown. - STATE_CONNECTED (1): - Connected. - STATE_CONNECTING (2): - Still connecting. - STATE_ERROR (3): - Error occurred. - """ - STATE_UNSPECIFIED = 0 - STATE_CONNECTED = 1 - STATE_CONNECTING = 2 - STATE_ERROR = 3 - - class CloudRouter(proto.Message): - r"""The Cloud Router info. - - Attributes: - name (str): - The associated Cloud Router name. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - class CloudVpn(proto.Message): - r"""The Cloud VPN info. - - Attributes: - gateway (str): - The created Cloud VPN gateway name. - """ - - gateway: str = proto.Field( - proto.STRING, - number=1, - ) - - state: 'VpnConnection.Details.State' = proto.Field( - proto.ENUM, - number=1, - enum='VpnConnection.Details.State', - ) - error: str = proto.Field( - proto.STRING, - number=2, - ) - cloud_router: 'VpnConnection.Details.CloudRouter' = proto.Field( - proto.MESSAGE, - number=3, - message='VpnConnection.Details.CloudRouter', - ) - cloud_vpns: MutableSequence['VpnConnection.Details.CloudVpn'] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='VpnConnection.Details.CloudVpn', - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - labels: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=4, - ) - nat_gateway_ip: str = proto.Field( - proto.STRING, - number=5, - ) - bgp_routing_mode: BgpRoutingMode = proto.Field( - proto.ENUM, - number=6, - enum=BgpRoutingMode, - ) - cluster: str = proto.Field( - proto.STRING, - number=7, - ) - vpc: str = proto.Field( - proto.STRING, - number=8, - ) - vpc_project: VpcProject = proto.Field( - proto.MESSAGE, - number=11, - message=VpcProject, - ) - enable_high_availability: bool = proto.Field( - proto.BOOL, - number=9, - ) - router: str = proto.Field( - proto.STRING, - number=12, - ) - details: Details = proto.Field( - proto.MESSAGE, - number=10, - message=Details, - ) - - -class LocationMetadata(proto.Message): - r"""Metadata for a given - [google.cloud.location.Location][google.cloud.location.Location]. - - Attributes: - available_zones (MutableMapping[str, google.cloud.edgecontainer_v1.types.ZoneMetadata]): - The set of available Google Distributed Cloud - Edge zones in the location. The map is keyed by - the lowercase ID of each zone. - """ - - available_zones: MutableMapping[str, 'ZoneMetadata'] = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=1, - message='ZoneMetadata', - ) - - -class ZoneMetadata(proto.Message): - r"""A Google Distributed Cloud Edge zone where edge machines are - located. - - Attributes: - quota (MutableSequence[google.cloud.edgecontainer_v1.types.Quota]): - Quota for resources in this zone. - rack_types (MutableMapping[str, google.cloud.edgecontainer_v1.types.ZoneMetadata.RackType]): - The map keyed by rack name and has value of - RackType. - """ - class RackType(proto.Enum): - r"""Type of the rack. - - Values: - RACK_TYPE_UNSPECIFIED (0): - Unspecified rack type, single rack also - belongs to this type. - BASE (1): - Base rack type, a pair of two modified - Config-1 racks containing Aggregation switches. - EXPANSION (2): - Expansion rack type, also known as standalone - racks, added by customers on demand. - """ - RACK_TYPE_UNSPECIFIED = 0 - BASE = 1 - EXPANSION = 2 - - quota: MutableSequence['Quota'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Quota', - ) - rack_types: MutableMapping[str, RackType] = proto.MapField( - proto.STRING, - proto.ENUM, - number=2, - enum=RackType, - ) - - -class Quota(proto.Message): - r"""Represents quota for Edge Container resources. - - Attributes: - metric (str): - Name of the quota metric. - limit (float): - Quota limit for this metric. - usage (float): - Current usage of this metric. - """ - - metric: str = proto.Field( - proto.STRING, - number=1, - ) - limit: float = proto.Field( - proto.DOUBLE, - number=2, - ) - usage: float = proto.Field( - proto.DOUBLE, - number=3, - ) - - -class MaintenancePolicy(proto.Message): - r"""Maintenance policy configuration. - - Attributes: - window (google.cloud.edgecontainer_v1.types.MaintenanceWindow): - Specifies the maintenance window in which - maintenance may be performed. - """ - - window: 'MaintenanceWindow' = proto.Field( - proto.MESSAGE, - number=1, - message='MaintenanceWindow', - ) - - -class MaintenanceWindow(proto.Message): - r"""Maintenance window configuration - - Attributes: - recurring_window (google.cloud.edgecontainer_v1.types.RecurringTimeWindow): - Configuration of a recurring maintenance - window. - """ - - recurring_window: 'RecurringTimeWindow' = proto.Field( - proto.MESSAGE, - number=1, - message='RecurringTimeWindow', - ) - - -class RecurringTimeWindow(proto.Message): - r"""Represents an arbitrary window of time that recurs. - - Attributes: - window (google.cloud.edgecontainer_v1.types.TimeWindow): - The window of the first recurrence. - recurrence (str): - An RRULE - (https://tools.ietf.org/html/rfc5545#section-3.8.5.3) - for how this window recurs. They go on for the - span of time between the start and end time. - """ - - window: 'TimeWindow' = proto.Field( - proto.MESSAGE, - number=1, - message='TimeWindow', - ) - recurrence: str = proto.Field( - proto.STRING, - number=2, - ) - - -class TimeWindow(proto.Message): - r"""Represents an arbitrary window of time. - - Attributes: - start_time (google.protobuf.timestamp_pb2.Timestamp): - The time that the window first starts. - end_time (google.protobuf.timestamp_pb2.Timestamp): - The time that the window ends. The end time - must take place after the start time. - """ - - start_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - end_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - - -class ServerConfig(proto.Message): - r"""Server configuration for supported versions and release - channels. - - Attributes: - channels (MutableMapping[str, google.cloud.edgecontainer_v1.types.ChannelConfig]): - Output only. Mapping from release channel to - channel config. - versions (MutableSequence[google.cloud.edgecontainer_v1.types.Version]): - Output only. Supported versions, e.g.: ["1.4.0", "1.5.0"]. - default_version (str): - Output only. Default version, e.g.: "1.4.0". - """ - - channels: MutableMapping[str, 'ChannelConfig'] = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=1, - message='ChannelConfig', - ) - versions: MutableSequence['Version'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='Version', - ) - default_version: str = proto.Field( - proto.STRING, - number=3, - ) - - -class ChannelConfig(proto.Message): - r"""Configuration for a release channel. - - Attributes: - default_version (str): - Output only. Default version for this release - channel, e.g.: "1.4.0". - """ - - default_version: str = proto.Field( - proto.STRING, - number=1, - ) - - -class Version(proto.Message): - r"""Version of a cluster. - - Attributes: - name (str): - Output only. Name of the version, e.g.: - "1.4.0". - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-edgecontainer/v1/google/cloud/edgecontainer_v1/types/service.py b/owl-bot-staging/google-cloud-edgecontainer/v1/google/cloud/edgecontainer_v1/types/service.py deleted file mode 100644 index 1cfead12dbf4..000000000000 --- a/owl-bot-staging/google-cloud-edgecontainer/v1/google/cloud/edgecontainer_v1/types/service.py +++ /dev/null @@ -1,879 +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.cloud.edgecontainer_v1.types import resources -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.edgecontainer.v1', - manifest={ - 'OperationMetadata', - 'ListClustersRequest', - 'ListClustersResponse', - 'GetClusterRequest', - 'CreateClusterRequest', - 'UpdateClusterRequest', - 'UpgradeClusterRequest', - 'DeleteClusterRequest', - 'GenerateAccessTokenRequest', - 'GenerateAccessTokenResponse', - 'GenerateOfflineCredentialRequest', - 'GenerateOfflineCredentialResponse', - 'ListNodePoolsRequest', - 'ListNodePoolsResponse', - 'GetNodePoolRequest', - 'CreateNodePoolRequest', - 'UpdateNodePoolRequest', - 'DeleteNodePoolRequest', - 'ListMachinesRequest', - 'ListMachinesResponse', - 'GetMachineRequest', - 'ListVpnConnectionsRequest', - 'ListVpnConnectionsResponse', - 'GetVpnConnectionRequest', - 'CreateVpnConnectionRequest', - 'DeleteVpnConnectionRequest', - 'GetServerConfigRequest', - }, -) - - -class OperationMetadata(proto.Message): - r"""Long-running operation metadata for Edge Container API - methods. - - Attributes: - create_time (google.protobuf.timestamp_pb2.Timestamp): - The time the operation was created. - end_time (google.protobuf.timestamp_pb2.Timestamp): - The time the operation finished running. - target (str): - Server-defined resource path for the target - of the operation. - verb (str): - The verb executed by the operation. - status_message (str): - Human-readable status of the operation, if - any. - requested_cancellation (bool): - Identifies whether the user has requested cancellation of - the operation. Operations that have successfully been - cancelled have [Operation.error][] value with a - [google.rpc.Status.code][google.rpc.Status.code] of 1, - corresponding to ``Code.CANCELLED``. - api_version (str): - API version used to start the operation. - warnings (MutableSequence[str]): - Warnings that do not block the operation, but - still hold relevant information for the end user - to receive. - """ - - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - end_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - target: str = proto.Field( - proto.STRING, - number=3, - ) - verb: str = proto.Field( - proto.STRING, - number=4, - ) - status_message: str = proto.Field( - proto.STRING, - number=5, - ) - requested_cancellation: bool = proto.Field( - proto.BOOL, - number=6, - ) - api_version: str = proto.Field( - proto.STRING, - number=7, - ) - warnings: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=8, - ) - - -class ListClustersRequest(proto.Message): - r"""Lists clusters in a location. - - Attributes: - parent (str): - Required. The parent location, which owns - this collection of clusters. - page_size (int): - The maximum number of resources to list. - page_token (str): - A page token received from previous list - request. A page token received from previous - list request. - filter (str): - Only resources matching this filter will be - listed. - order_by (str): - Specifies the order in which resources will - be listed. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - page_size: int = proto.Field( - proto.INT32, - number=2, - ) - page_token: str = proto.Field( - proto.STRING, - number=3, - ) - filter: str = proto.Field( - proto.STRING, - number=4, - ) - order_by: str = proto.Field( - proto.STRING, - number=5, - ) - - -class ListClustersResponse(proto.Message): - r"""List of clusters in a location. - - Attributes: - clusters (MutableSequence[google.cloud.edgecontainer_v1.types.Cluster]): - Clusters in the location. - next_page_token (str): - A token to retrieve next page of results. - unreachable (MutableSequence[str]): - Locations that could not be reached. - """ - - @property - def raw_page(self): - return self - - clusters: MutableSequence[resources.Cluster] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=resources.Cluster, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - unreachable: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - - -class GetClusterRequest(proto.Message): - r"""Gets a cluster. - - Attributes: - name (str): - Required. The resource name of the cluster. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class CreateClusterRequest(proto.Message): - r"""Creates a cluster. - - Attributes: - parent (str): - Required. The parent location where this - cluster will be created. - cluster_id (str): - Required. A client-specified unique - identifier for the cluster. - cluster (google.cloud.edgecontainer_v1.types.Cluster): - Required. The cluster to create. - request_id (str): - A unique identifier for this request. Restricted to 36 ASCII - characters. A random UUID is recommended. This request is - only idempotent if ``request_id`` is provided. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - cluster_id: str = proto.Field( - proto.STRING, - number=2, - ) - cluster: resources.Cluster = proto.Field( - proto.MESSAGE, - number=3, - message=resources.Cluster, - ) - request_id: str = proto.Field( - proto.STRING, - number=4, - ) - - -class UpdateClusterRequest(proto.Message): - r"""Updates a cluster. - - Attributes: - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Field mask is used to specify the fields to be overwritten - in the Cluster resource by the update. The fields specified - in the update_mask are relative to the resource, not the - full request. A field will be overwritten if it is in the - mask. If the user does not provide a mask then all fields - will be overwritten. - cluster (google.cloud.edgecontainer_v1.types.Cluster): - The updated cluster. - request_id (str): - A unique identifier for this request. Restricted to 36 ASCII - characters. A random UUID is recommended. This request is - only idempotent if ``request_id`` is provided. - """ - - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=1, - message=field_mask_pb2.FieldMask, - ) - cluster: resources.Cluster = proto.Field( - proto.MESSAGE, - number=2, - message=resources.Cluster, - ) - request_id: str = proto.Field( - proto.STRING, - number=3, - ) - - -class UpgradeClusterRequest(proto.Message): - r"""Upgrades a cluster. - - Attributes: - name (str): - Required. The resource name of the cluster. - target_version (str): - Required. The version the cluster is going to - be upgraded to. - schedule (google.cloud.edgecontainer_v1.types.UpgradeClusterRequest.Schedule): - The schedule for the upgrade. - request_id (str): - A unique identifier for this request. Restricted to 36 ASCII - characters. A random UUID is recommended. This request is - only idempotent if ``request_id`` is provided. - """ - class Schedule(proto.Enum): - r"""Represents the schedule about when the cluster is going to be - upgraded. - - Values: - SCHEDULE_UNSPECIFIED (0): - Unspecified. The default is to upgrade the - cluster immediately which is the only option - today. - IMMEDIATELY (1): - The cluster is going to be upgraded - immediately after receiving the request. - """ - SCHEDULE_UNSPECIFIED = 0 - IMMEDIATELY = 1 - - name: str = proto.Field( - proto.STRING, - number=1, - ) - target_version: str = proto.Field( - proto.STRING, - number=2, - ) - schedule: Schedule = proto.Field( - proto.ENUM, - number=3, - enum=Schedule, - ) - request_id: str = proto.Field( - proto.STRING, - number=4, - ) - - -class DeleteClusterRequest(proto.Message): - r"""Deletes a cluster. - - Attributes: - name (str): - Required. The resource name of the cluster. - request_id (str): - A unique identifier for this request. Restricted to 36 ASCII - characters. A random UUID is recommended. This request is - only idempotent if ``request_id`` is provided. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - request_id: str = proto.Field( - proto.STRING, - number=2, - ) - - -class GenerateAccessTokenRequest(proto.Message): - r"""Generates an access token for a cluster. - - Attributes: - cluster (str): - Required. The resource name of the cluster. - """ - - cluster: str = proto.Field( - proto.STRING, - number=1, - ) - - -class GenerateAccessTokenResponse(proto.Message): - r"""An access token for a cluster. - - Attributes: - access_token (str): - Output only. Access token to authenticate to - k8s api-server. - expire_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Timestamp at which the token - will expire. - """ - - access_token: str = proto.Field( - proto.STRING, - number=1, - ) - expire_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - - -class GenerateOfflineCredentialRequest(proto.Message): - r"""Generates an offline credential(offline) for a cluster. - - Attributes: - cluster (str): - Required. The resource name of the cluster. - """ - - cluster: str = proto.Field( - proto.STRING, - number=1, - ) - - -class GenerateOfflineCredentialResponse(proto.Message): - r"""An offline credential for a cluster. - - Attributes: - client_certificate (str): - Output only. Client certificate to - authenticate to k8s api-server. - client_key (str): - Output only. Client private key to - authenticate to k8s api-server. - user_id (str): - Output only. Client's identity. - expire_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Timestamp at which this - credential will expire. - """ - - client_certificate: str = proto.Field( - proto.STRING, - number=1, - ) - client_key: str = proto.Field( - proto.STRING, - number=2, - ) - user_id: str = proto.Field( - proto.STRING, - number=3, - ) - expire_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - - -class ListNodePoolsRequest(proto.Message): - r"""Lists node pools in a cluster. - - Attributes: - parent (str): - Required. The parent cluster, which owns this - collection of node pools. - page_size (int): - The maximum number of resources to list. - page_token (str): - A page token received from previous list - request. - filter (str): - Only resources matching this filter will be - listed. - order_by (str): - Specifies the order in which resources will - be listed. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - page_size: int = proto.Field( - proto.INT32, - number=2, - ) - page_token: str = proto.Field( - proto.STRING, - number=3, - ) - filter: str = proto.Field( - proto.STRING, - number=4, - ) - order_by: str = proto.Field( - proto.STRING, - number=5, - ) - - -class ListNodePoolsResponse(proto.Message): - r"""List of node pools in a cluster. - - Attributes: - node_pools (MutableSequence[google.cloud.edgecontainer_v1.types.NodePool]): - Node pools in the cluster. - next_page_token (str): - A token to retrieve next page of results. - unreachable (MutableSequence[str]): - Locations that could not be reached. - """ - - @property - def raw_page(self): - return self - - node_pools: MutableSequence[resources.NodePool] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=resources.NodePool, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - unreachable: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - - -class GetNodePoolRequest(proto.Message): - r"""Gets a node pool. - - Attributes: - name (str): - Required. The resource name of the node pool. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class CreateNodePoolRequest(proto.Message): - r"""Creates a node pool. - - Attributes: - parent (str): - Required. The parent cluster where this node - pool will be created. - node_pool_id (str): - Required. A client-specified unique - identifier for the node pool. - node_pool (google.cloud.edgecontainer_v1.types.NodePool): - Required. The node pool to create. - request_id (str): - A unique identifier for this request. Restricted to 36 ASCII - characters. A random UUID is recommended. This request is - only idempotent if ``request_id`` is provided. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - node_pool_id: str = proto.Field( - proto.STRING, - number=2, - ) - node_pool: resources.NodePool = proto.Field( - proto.MESSAGE, - number=3, - message=resources.NodePool, - ) - request_id: str = proto.Field( - proto.STRING, - number=4, - ) - - -class UpdateNodePoolRequest(proto.Message): - r"""Updates a node pool. - - Attributes: - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Field mask is used to specify the fields to be overwritten - in the NodePool resource by the update. The fields specified - in the update_mask are relative to the resource, not the - full request. A field will be overwritten if it is in the - mask. If the user does not provide a mask then all fields - will be overwritten. - node_pool (google.cloud.edgecontainer_v1.types.NodePool): - The updated node pool. - request_id (str): - A unique identifier for this request. Restricted to 36 ASCII - characters. A random UUID is recommended. This request is - only idempotent if ``request_id`` is provided. - """ - - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=1, - message=field_mask_pb2.FieldMask, - ) - node_pool: resources.NodePool = proto.Field( - proto.MESSAGE, - number=2, - message=resources.NodePool, - ) - request_id: str = proto.Field( - proto.STRING, - number=3, - ) - - -class DeleteNodePoolRequest(proto.Message): - r"""Deletes a node pool. - - Attributes: - name (str): - Required. The resource name of the node pool. - request_id (str): - A unique identifier for this request. Restricted to 36 ASCII - characters. A random UUID is recommended. This request is - only idempotent if ``request_id`` is provided. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - request_id: str = proto.Field( - proto.STRING, - number=2, - ) - - -class ListMachinesRequest(proto.Message): - r"""Lists machines in a site. - - Attributes: - parent (str): - Required. The parent site, which owns this - collection of machines. - page_size (int): - The maximum number of resources to list. - page_token (str): - A page token received from previous list - request. - filter (str): - Only resources matching this filter will be - listed. - order_by (str): - Specifies the order in which resources will - be listed. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - page_size: int = proto.Field( - proto.INT32, - number=2, - ) - page_token: str = proto.Field( - proto.STRING, - number=3, - ) - filter: str = proto.Field( - proto.STRING, - number=4, - ) - order_by: str = proto.Field( - proto.STRING, - number=5, - ) - - -class ListMachinesResponse(proto.Message): - r"""List of machines in a site. - - Attributes: - machines (MutableSequence[google.cloud.edgecontainer_v1.types.Machine]): - Machines in the site. - next_page_token (str): - A token to retrieve next page of results. - unreachable (MutableSequence[str]): - Locations that could not be reached. - """ - - @property - def raw_page(self): - return self - - machines: MutableSequence[resources.Machine] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=resources.Machine, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - unreachable: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - - -class GetMachineRequest(proto.Message): - r"""Gets a machine. - - Attributes: - name (str): - Required. The resource name of the machine. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListVpnConnectionsRequest(proto.Message): - r"""Lists VPN connections. - - Attributes: - parent (str): - Required. The parent location, which owns - this collection of VPN connections. - page_size (int): - The maximum number of resources to list. - page_token (str): - A page token received from previous list - request. - filter (str): - Only resources matching this filter will be - listed. - order_by (str): - Specifies the order in which resources will - be listed. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - page_size: int = proto.Field( - proto.INT32, - number=2, - ) - page_token: str = proto.Field( - proto.STRING, - number=3, - ) - filter: str = proto.Field( - proto.STRING, - number=4, - ) - order_by: str = proto.Field( - proto.STRING, - number=5, - ) - - -class ListVpnConnectionsResponse(proto.Message): - r"""List of VPN connections in a location. - - Attributes: - vpn_connections (MutableSequence[google.cloud.edgecontainer_v1.types.VpnConnection]): - VpnConnections in the location. - next_page_token (str): - A token to retrieve next page of results. - unreachable (MutableSequence[str]): - Locations that could not be reached. - """ - - @property - def raw_page(self): - return self - - vpn_connections: MutableSequence[resources.VpnConnection] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=resources.VpnConnection, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - unreachable: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - - -class GetVpnConnectionRequest(proto.Message): - r"""Gets a VPN connection. - - Attributes: - name (str): - Required. The resource name of the vpn - connection. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class CreateVpnConnectionRequest(proto.Message): - r"""Creates a VPN connection. - - Attributes: - parent (str): - Required. The parent location where this vpn - connection will be created. - vpn_connection_id (str): - Required. The VPN connection identifier. - vpn_connection (google.cloud.edgecontainer_v1.types.VpnConnection): - Required. The VPN connection to create. - request_id (str): - A unique identifier for this request. Restricted to 36 ASCII - characters. A random UUID is recommended. This request is - only idempotent if ``request_id`` is provided. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - vpn_connection_id: str = proto.Field( - proto.STRING, - number=2, - ) - vpn_connection: resources.VpnConnection = proto.Field( - proto.MESSAGE, - number=3, - message=resources.VpnConnection, - ) - request_id: str = proto.Field( - proto.STRING, - number=4, - ) - - -class DeleteVpnConnectionRequest(proto.Message): - r"""Deletes a vpn connection. - - Attributes: - name (str): - Required. The resource name of the vpn - connection. - request_id (str): - A unique identifier for this request. Restricted to 36 ASCII - characters. A random UUID is recommended. This request is - only idempotent if ``request_id`` is provided. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - request_id: str = proto.Field( - proto.STRING, - number=2, - ) - - -class GetServerConfigRequest(proto.Message): - r"""Gets the server config. - - Attributes: - name (str): - Required. The name (project and location) of the server - config to get, specified in the format - ``projects/*/locations/*``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-edgecontainer/v1/mypy.ini b/owl-bot-staging/google-cloud-edgecontainer/v1/mypy.ini deleted file mode 100644 index 574c5aed394b..000000000000 --- a/owl-bot-staging/google-cloud-edgecontainer/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-edgecontainer/v1/noxfile.py b/owl-bot-staging/google-cloud-edgecontainer/v1/noxfile.py deleted file mode 100644 index e1b85b21736e..000000000000 --- a/owl-bot-staging/google-cloud-edgecontainer/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-edgecontainer' - -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/edgecontainer_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/edgecontainer_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-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_create_cluster_async.py b/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_create_cluster_async.py deleted file mode 100644 index 477c255308b1..000000000000 --- a/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_create_cluster_async.py +++ /dev/null @@ -1,65 +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 CreateCluster -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-edgecontainer - - -# [START edgecontainer_v1_generated_EdgeContainer_CreateCluster_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 edgecontainer_v1 - - -async def sample_create_cluster(): - # Create a client - client = edgecontainer_v1.EdgeContainerAsyncClient() - - # Initialize request argument(s) - cluster = edgecontainer_v1.Cluster() - cluster.name = "name_value" - cluster.fleet.project = "project_value" - cluster.networking.cluster_ipv4_cidr_blocks = ['cluster_ipv4_cidr_blocks_value1', 'cluster_ipv4_cidr_blocks_value2'] - cluster.networking.services_ipv4_cidr_blocks = ['services_ipv4_cidr_blocks_value1', 'services_ipv4_cidr_blocks_value2'] - cluster.authorization.admin_users.username = "username_value" - - request = edgecontainer_v1.CreateClusterRequest( - parent="parent_value", - cluster_id="cluster_id_value", - cluster=cluster, - ) - - # Make the request - operation = client.create_cluster(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END edgecontainer_v1_generated_EdgeContainer_CreateCluster_async] diff --git a/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_create_cluster_sync.py b/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_create_cluster_sync.py deleted file mode 100644 index 4ad21d65071d..000000000000 --- a/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_create_cluster_sync.py +++ /dev/null @@ -1,65 +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 CreateCluster -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-edgecontainer - - -# [START edgecontainer_v1_generated_EdgeContainer_CreateCluster_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 edgecontainer_v1 - - -def sample_create_cluster(): - # Create a client - client = edgecontainer_v1.EdgeContainerClient() - - # Initialize request argument(s) - cluster = edgecontainer_v1.Cluster() - cluster.name = "name_value" - cluster.fleet.project = "project_value" - cluster.networking.cluster_ipv4_cidr_blocks = ['cluster_ipv4_cidr_blocks_value1', 'cluster_ipv4_cidr_blocks_value2'] - cluster.networking.services_ipv4_cidr_blocks = ['services_ipv4_cidr_blocks_value1', 'services_ipv4_cidr_blocks_value2'] - cluster.authorization.admin_users.username = "username_value" - - request = edgecontainer_v1.CreateClusterRequest( - parent="parent_value", - cluster_id="cluster_id_value", - cluster=cluster, - ) - - # Make the request - operation = client.create_cluster(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END edgecontainer_v1_generated_EdgeContainer_CreateCluster_sync] diff --git a/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_create_node_pool_async.py b/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_create_node_pool_async.py deleted file mode 100644 index 85f6f78c44a9..000000000000 --- a/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_create_node_pool_async.py +++ /dev/null @@ -1,62 +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 CreateNodePool -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-edgecontainer - - -# [START edgecontainer_v1_generated_EdgeContainer_CreateNodePool_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 edgecontainer_v1 - - -async def sample_create_node_pool(): - # Create a client - client = edgecontainer_v1.EdgeContainerAsyncClient() - - # Initialize request argument(s) - node_pool = edgecontainer_v1.NodePool() - node_pool.name = "name_value" - node_pool.node_count = 1070 - - request = edgecontainer_v1.CreateNodePoolRequest( - parent="parent_value", - node_pool_id="node_pool_id_value", - node_pool=node_pool, - ) - - # Make the request - operation = client.create_node_pool(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END edgecontainer_v1_generated_EdgeContainer_CreateNodePool_async] diff --git a/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_create_node_pool_sync.py b/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_create_node_pool_sync.py deleted file mode 100644 index d5530f8c4bdf..000000000000 --- a/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_create_node_pool_sync.py +++ /dev/null @@ -1,62 +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 CreateNodePool -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-edgecontainer - - -# [START edgecontainer_v1_generated_EdgeContainer_CreateNodePool_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 edgecontainer_v1 - - -def sample_create_node_pool(): - # Create a client - client = edgecontainer_v1.EdgeContainerClient() - - # Initialize request argument(s) - node_pool = edgecontainer_v1.NodePool() - node_pool.name = "name_value" - node_pool.node_count = 1070 - - request = edgecontainer_v1.CreateNodePoolRequest( - parent="parent_value", - node_pool_id="node_pool_id_value", - node_pool=node_pool, - ) - - # Make the request - operation = client.create_node_pool(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END edgecontainer_v1_generated_EdgeContainer_CreateNodePool_sync] diff --git a/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_create_vpn_connection_async.py b/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_create_vpn_connection_async.py deleted file mode 100644 index ec45418d7e05..000000000000 --- a/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_create_vpn_connection_async.py +++ /dev/null @@ -1,61 +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 CreateVpnConnection -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-edgecontainer - - -# [START edgecontainer_v1_generated_EdgeContainer_CreateVpnConnection_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 edgecontainer_v1 - - -async def sample_create_vpn_connection(): - # Create a client - client = edgecontainer_v1.EdgeContainerAsyncClient() - - # Initialize request argument(s) - vpn_connection = edgecontainer_v1.VpnConnection() - vpn_connection.name = "name_value" - - request = edgecontainer_v1.CreateVpnConnectionRequest( - parent="parent_value", - vpn_connection_id="vpn_connection_id_value", - vpn_connection=vpn_connection, - ) - - # Make the request - operation = client.create_vpn_connection(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END edgecontainer_v1_generated_EdgeContainer_CreateVpnConnection_async] diff --git a/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_create_vpn_connection_sync.py b/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_create_vpn_connection_sync.py deleted file mode 100644 index 19bfa565d891..000000000000 --- a/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_create_vpn_connection_sync.py +++ /dev/null @@ -1,61 +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 CreateVpnConnection -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-edgecontainer - - -# [START edgecontainer_v1_generated_EdgeContainer_CreateVpnConnection_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 edgecontainer_v1 - - -def sample_create_vpn_connection(): - # Create a client - client = edgecontainer_v1.EdgeContainerClient() - - # Initialize request argument(s) - vpn_connection = edgecontainer_v1.VpnConnection() - vpn_connection.name = "name_value" - - request = edgecontainer_v1.CreateVpnConnectionRequest( - parent="parent_value", - vpn_connection_id="vpn_connection_id_value", - vpn_connection=vpn_connection, - ) - - # Make the request - operation = client.create_vpn_connection(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END edgecontainer_v1_generated_EdgeContainer_CreateVpnConnection_sync] diff --git a/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_delete_cluster_async.py b/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_delete_cluster_async.py deleted file mode 100644 index 6190130dc9a4..000000000000 --- a/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_delete_cluster_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 DeleteCluster -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-edgecontainer - - -# [START edgecontainer_v1_generated_EdgeContainer_DeleteCluster_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 edgecontainer_v1 - - -async def sample_delete_cluster(): - # Create a client - client = edgecontainer_v1.EdgeContainerAsyncClient() - - # Initialize request argument(s) - request = edgecontainer_v1.DeleteClusterRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_cluster(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END edgecontainer_v1_generated_EdgeContainer_DeleteCluster_async] diff --git a/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_delete_cluster_sync.py b/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_delete_cluster_sync.py deleted file mode 100644 index d35bb24d57fa..000000000000 --- a/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_delete_cluster_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 DeleteCluster -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-edgecontainer - - -# [START edgecontainer_v1_generated_EdgeContainer_DeleteCluster_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 edgecontainer_v1 - - -def sample_delete_cluster(): - # Create a client - client = edgecontainer_v1.EdgeContainerClient() - - # Initialize request argument(s) - request = edgecontainer_v1.DeleteClusterRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_cluster(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END edgecontainer_v1_generated_EdgeContainer_DeleteCluster_sync] diff --git a/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_delete_node_pool_async.py b/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_delete_node_pool_async.py deleted file mode 100644 index 4e4981e4a2b1..000000000000 --- a/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_delete_node_pool_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 DeleteNodePool -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-edgecontainer - - -# [START edgecontainer_v1_generated_EdgeContainer_DeleteNodePool_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 edgecontainer_v1 - - -async def sample_delete_node_pool(): - # Create a client - client = edgecontainer_v1.EdgeContainerAsyncClient() - - # Initialize request argument(s) - request = edgecontainer_v1.DeleteNodePoolRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_node_pool(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END edgecontainer_v1_generated_EdgeContainer_DeleteNodePool_async] diff --git a/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_delete_node_pool_sync.py b/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_delete_node_pool_sync.py deleted file mode 100644 index 1611179df6bd..000000000000 --- a/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_delete_node_pool_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 DeleteNodePool -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-edgecontainer - - -# [START edgecontainer_v1_generated_EdgeContainer_DeleteNodePool_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 edgecontainer_v1 - - -def sample_delete_node_pool(): - # Create a client - client = edgecontainer_v1.EdgeContainerClient() - - # Initialize request argument(s) - request = edgecontainer_v1.DeleteNodePoolRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_node_pool(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END edgecontainer_v1_generated_EdgeContainer_DeleteNodePool_sync] diff --git a/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_delete_vpn_connection_async.py b/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_delete_vpn_connection_async.py deleted file mode 100644 index d4e0209bee97..000000000000 --- a/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_delete_vpn_connection_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 DeleteVpnConnection -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-edgecontainer - - -# [START edgecontainer_v1_generated_EdgeContainer_DeleteVpnConnection_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 edgecontainer_v1 - - -async def sample_delete_vpn_connection(): - # Create a client - client = edgecontainer_v1.EdgeContainerAsyncClient() - - # Initialize request argument(s) - request = edgecontainer_v1.DeleteVpnConnectionRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_vpn_connection(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END edgecontainer_v1_generated_EdgeContainer_DeleteVpnConnection_async] diff --git a/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_delete_vpn_connection_sync.py b/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_delete_vpn_connection_sync.py deleted file mode 100644 index 877e5abfac9c..000000000000 --- a/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_delete_vpn_connection_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 DeleteVpnConnection -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-edgecontainer - - -# [START edgecontainer_v1_generated_EdgeContainer_DeleteVpnConnection_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 edgecontainer_v1 - - -def sample_delete_vpn_connection(): - # Create a client - client = edgecontainer_v1.EdgeContainerClient() - - # Initialize request argument(s) - request = edgecontainer_v1.DeleteVpnConnectionRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_vpn_connection(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END edgecontainer_v1_generated_EdgeContainer_DeleteVpnConnection_sync] diff --git a/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_generate_access_token_async.py b/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_generate_access_token_async.py deleted file mode 100644 index ad4c0e127366..000000000000 --- a/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_generate_access_token_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 GenerateAccessToken -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-edgecontainer - - -# [START edgecontainer_v1_generated_EdgeContainer_GenerateAccessToken_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 edgecontainer_v1 - - -async def sample_generate_access_token(): - # Create a client - client = edgecontainer_v1.EdgeContainerAsyncClient() - - # Initialize request argument(s) - request = edgecontainer_v1.GenerateAccessTokenRequest( - cluster="cluster_value", - ) - - # Make the request - response = await client.generate_access_token(request=request) - - # Handle the response - print(response) - -# [END edgecontainer_v1_generated_EdgeContainer_GenerateAccessToken_async] diff --git a/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_generate_access_token_sync.py b/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_generate_access_token_sync.py deleted file mode 100644 index f26ea0abc9ad..000000000000 --- a/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_generate_access_token_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 GenerateAccessToken -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-edgecontainer - - -# [START edgecontainer_v1_generated_EdgeContainer_GenerateAccessToken_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 edgecontainer_v1 - - -def sample_generate_access_token(): - # Create a client - client = edgecontainer_v1.EdgeContainerClient() - - # Initialize request argument(s) - request = edgecontainer_v1.GenerateAccessTokenRequest( - cluster="cluster_value", - ) - - # Make the request - response = client.generate_access_token(request=request) - - # Handle the response - print(response) - -# [END edgecontainer_v1_generated_EdgeContainer_GenerateAccessToken_sync] diff --git a/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_generate_offline_credential_async.py b/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_generate_offline_credential_async.py deleted file mode 100644 index db0de182ef47..000000000000 --- a/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_generate_offline_credential_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 GenerateOfflineCredential -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-edgecontainer - - -# [START edgecontainer_v1_generated_EdgeContainer_GenerateOfflineCredential_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 edgecontainer_v1 - - -async def sample_generate_offline_credential(): - # Create a client - client = edgecontainer_v1.EdgeContainerAsyncClient() - - # Initialize request argument(s) - request = edgecontainer_v1.GenerateOfflineCredentialRequest( - cluster="cluster_value", - ) - - # Make the request - response = await client.generate_offline_credential(request=request) - - # Handle the response - print(response) - -# [END edgecontainer_v1_generated_EdgeContainer_GenerateOfflineCredential_async] diff --git a/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_generate_offline_credential_sync.py b/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_generate_offline_credential_sync.py deleted file mode 100644 index 809de663b244..000000000000 --- a/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_generate_offline_credential_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 GenerateOfflineCredential -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-edgecontainer - - -# [START edgecontainer_v1_generated_EdgeContainer_GenerateOfflineCredential_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 edgecontainer_v1 - - -def sample_generate_offline_credential(): - # Create a client - client = edgecontainer_v1.EdgeContainerClient() - - # Initialize request argument(s) - request = edgecontainer_v1.GenerateOfflineCredentialRequest( - cluster="cluster_value", - ) - - # Make the request - response = client.generate_offline_credential(request=request) - - # Handle the response - print(response) - -# [END edgecontainer_v1_generated_EdgeContainer_GenerateOfflineCredential_sync] diff --git a/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_get_cluster_async.py b/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_get_cluster_async.py deleted file mode 100644 index 265792361ed7..000000000000 --- a/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_get_cluster_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 GetCluster -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-edgecontainer - - -# [START edgecontainer_v1_generated_EdgeContainer_GetCluster_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 edgecontainer_v1 - - -async def sample_get_cluster(): - # Create a client - client = edgecontainer_v1.EdgeContainerAsyncClient() - - # Initialize request argument(s) - request = edgecontainer_v1.GetClusterRequest( - name="name_value", - ) - - # Make the request - response = await client.get_cluster(request=request) - - # Handle the response - print(response) - -# [END edgecontainer_v1_generated_EdgeContainer_GetCluster_async] diff --git a/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_get_cluster_sync.py b/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_get_cluster_sync.py deleted file mode 100644 index 512f3dd3c73e..000000000000 --- a/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_get_cluster_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 GetCluster -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-edgecontainer - - -# [START edgecontainer_v1_generated_EdgeContainer_GetCluster_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 edgecontainer_v1 - - -def sample_get_cluster(): - # Create a client - client = edgecontainer_v1.EdgeContainerClient() - - # Initialize request argument(s) - request = edgecontainer_v1.GetClusterRequest( - name="name_value", - ) - - # Make the request - response = client.get_cluster(request=request) - - # Handle the response - print(response) - -# [END edgecontainer_v1_generated_EdgeContainer_GetCluster_sync] diff --git a/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_get_machine_async.py b/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_get_machine_async.py deleted file mode 100644 index a90c1832b93c..000000000000 --- a/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_get_machine_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 GetMachine -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-edgecontainer - - -# [START edgecontainer_v1_generated_EdgeContainer_GetMachine_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 edgecontainer_v1 - - -async def sample_get_machine(): - # Create a client - client = edgecontainer_v1.EdgeContainerAsyncClient() - - # Initialize request argument(s) - request = edgecontainer_v1.GetMachineRequest( - name="name_value", - ) - - # Make the request - response = await client.get_machine(request=request) - - # Handle the response - print(response) - -# [END edgecontainer_v1_generated_EdgeContainer_GetMachine_async] diff --git a/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_get_machine_sync.py b/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_get_machine_sync.py deleted file mode 100644 index dc2bab0568d1..000000000000 --- a/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_get_machine_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 GetMachine -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-edgecontainer - - -# [START edgecontainer_v1_generated_EdgeContainer_GetMachine_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 edgecontainer_v1 - - -def sample_get_machine(): - # Create a client - client = edgecontainer_v1.EdgeContainerClient() - - # Initialize request argument(s) - request = edgecontainer_v1.GetMachineRequest( - name="name_value", - ) - - # Make the request - response = client.get_machine(request=request) - - # Handle the response - print(response) - -# [END edgecontainer_v1_generated_EdgeContainer_GetMachine_sync] diff --git a/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_get_node_pool_async.py b/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_get_node_pool_async.py deleted file mode 100644 index 257683a83a40..000000000000 --- a/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_get_node_pool_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 GetNodePool -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-edgecontainer - - -# [START edgecontainer_v1_generated_EdgeContainer_GetNodePool_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 edgecontainer_v1 - - -async def sample_get_node_pool(): - # Create a client - client = edgecontainer_v1.EdgeContainerAsyncClient() - - # Initialize request argument(s) - request = edgecontainer_v1.GetNodePoolRequest( - name="name_value", - ) - - # Make the request - response = await client.get_node_pool(request=request) - - # Handle the response - print(response) - -# [END edgecontainer_v1_generated_EdgeContainer_GetNodePool_async] diff --git a/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_get_node_pool_sync.py b/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_get_node_pool_sync.py deleted file mode 100644 index 68f7d8b68402..000000000000 --- a/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_get_node_pool_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 GetNodePool -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-edgecontainer - - -# [START edgecontainer_v1_generated_EdgeContainer_GetNodePool_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 edgecontainer_v1 - - -def sample_get_node_pool(): - # Create a client - client = edgecontainer_v1.EdgeContainerClient() - - # Initialize request argument(s) - request = edgecontainer_v1.GetNodePoolRequest( - name="name_value", - ) - - # Make the request - response = client.get_node_pool(request=request) - - # Handle the response - print(response) - -# [END edgecontainer_v1_generated_EdgeContainer_GetNodePool_sync] diff --git a/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_get_server_config_async.py b/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_get_server_config_async.py deleted file mode 100644 index d2bfbe2b5a49..000000000000 --- a/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_get_server_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 GetServerConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-edgecontainer - - -# [START edgecontainer_v1_generated_EdgeContainer_GetServerConfig_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 edgecontainer_v1 - - -async def sample_get_server_config(): - # Create a client - client = edgecontainer_v1.EdgeContainerAsyncClient() - - # Initialize request argument(s) - request = edgecontainer_v1.GetServerConfigRequest( - name="name_value", - ) - - # Make the request - response = await client.get_server_config(request=request) - - # Handle the response - print(response) - -# [END edgecontainer_v1_generated_EdgeContainer_GetServerConfig_async] diff --git a/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_get_server_config_sync.py b/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_get_server_config_sync.py deleted file mode 100644 index f70aa41e9ba6..000000000000 --- a/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_get_server_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 GetServerConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-edgecontainer - - -# [START edgecontainer_v1_generated_EdgeContainer_GetServerConfig_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 edgecontainer_v1 - - -def sample_get_server_config(): - # Create a client - client = edgecontainer_v1.EdgeContainerClient() - - # Initialize request argument(s) - request = edgecontainer_v1.GetServerConfigRequest( - name="name_value", - ) - - # Make the request - response = client.get_server_config(request=request) - - # Handle the response - print(response) - -# [END edgecontainer_v1_generated_EdgeContainer_GetServerConfig_sync] diff --git a/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_get_vpn_connection_async.py b/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_get_vpn_connection_async.py deleted file mode 100644 index 0db16ec0243d..000000000000 --- a/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_get_vpn_connection_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 GetVpnConnection -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-edgecontainer - - -# [START edgecontainer_v1_generated_EdgeContainer_GetVpnConnection_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 edgecontainer_v1 - - -async def sample_get_vpn_connection(): - # Create a client - client = edgecontainer_v1.EdgeContainerAsyncClient() - - # Initialize request argument(s) - request = edgecontainer_v1.GetVpnConnectionRequest( - name="name_value", - ) - - # Make the request - response = await client.get_vpn_connection(request=request) - - # Handle the response - print(response) - -# [END edgecontainer_v1_generated_EdgeContainer_GetVpnConnection_async] diff --git a/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_get_vpn_connection_sync.py b/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_get_vpn_connection_sync.py deleted file mode 100644 index 9a89420a1508..000000000000 --- a/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_get_vpn_connection_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 GetVpnConnection -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-edgecontainer - - -# [START edgecontainer_v1_generated_EdgeContainer_GetVpnConnection_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 edgecontainer_v1 - - -def sample_get_vpn_connection(): - # Create a client - client = edgecontainer_v1.EdgeContainerClient() - - # Initialize request argument(s) - request = edgecontainer_v1.GetVpnConnectionRequest( - name="name_value", - ) - - # Make the request - response = client.get_vpn_connection(request=request) - - # Handle the response - print(response) - -# [END edgecontainer_v1_generated_EdgeContainer_GetVpnConnection_sync] diff --git a/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_list_clusters_async.py b/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_list_clusters_async.py deleted file mode 100644 index f0a9d5071b24..000000000000 --- a/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_list_clusters_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 ListClusters -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-edgecontainer - - -# [START edgecontainer_v1_generated_EdgeContainer_ListClusters_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 edgecontainer_v1 - - -async def sample_list_clusters(): - # Create a client - client = edgecontainer_v1.EdgeContainerAsyncClient() - - # Initialize request argument(s) - request = edgecontainer_v1.ListClustersRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_clusters(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END edgecontainer_v1_generated_EdgeContainer_ListClusters_async] diff --git a/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_list_clusters_sync.py b/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_list_clusters_sync.py deleted file mode 100644 index e5eef14639dc..000000000000 --- a/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_list_clusters_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 ListClusters -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-edgecontainer - - -# [START edgecontainer_v1_generated_EdgeContainer_ListClusters_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 edgecontainer_v1 - - -def sample_list_clusters(): - # Create a client - client = edgecontainer_v1.EdgeContainerClient() - - # Initialize request argument(s) - request = edgecontainer_v1.ListClustersRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_clusters(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END edgecontainer_v1_generated_EdgeContainer_ListClusters_sync] diff --git a/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_list_machines_async.py b/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_list_machines_async.py deleted file mode 100644 index 1ca455792901..000000000000 --- a/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_list_machines_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 ListMachines -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-edgecontainer - - -# [START edgecontainer_v1_generated_EdgeContainer_ListMachines_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 edgecontainer_v1 - - -async def sample_list_machines(): - # Create a client - client = edgecontainer_v1.EdgeContainerAsyncClient() - - # Initialize request argument(s) - request = edgecontainer_v1.ListMachinesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_machines(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END edgecontainer_v1_generated_EdgeContainer_ListMachines_async] diff --git a/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_list_machines_sync.py b/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_list_machines_sync.py deleted file mode 100644 index 762ac238c2cc..000000000000 --- a/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_list_machines_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 ListMachines -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-edgecontainer - - -# [START edgecontainer_v1_generated_EdgeContainer_ListMachines_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 edgecontainer_v1 - - -def sample_list_machines(): - # Create a client - client = edgecontainer_v1.EdgeContainerClient() - - # Initialize request argument(s) - request = edgecontainer_v1.ListMachinesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_machines(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END edgecontainer_v1_generated_EdgeContainer_ListMachines_sync] diff --git a/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_list_node_pools_async.py b/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_list_node_pools_async.py deleted file mode 100644 index e13966d05493..000000000000 --- a/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_list_node_pools_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 ListNodePools -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-edgecontainer - - -# [START edgecontainer_v1_generated_EdgeContainer_ListNodePools_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 edgecontainer_v1 - - -async def sample_list_node_pools(): - # Create a client - client = edgecontainer_v1.EdgeContainerAsyncClient() - - # Initialize request argument(s) - request = edgecontainer_v1.ListNodePoolsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_node_pools(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END edgecontainer_v1_generated_EdgeContainer_ListNodePools_async] diff --git a/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_list_node_pools_sync.py b/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_list_node_pools_sync.py deleted file mode 100644 index 93c766038ff1..000000000000 --- a/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_list_node_pools_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 ListNodePools -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-edgecontainer - - -# [START edgecontainer_v1_generated_EdgeContainer_ListNodePools_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 edgecontainer_v1 - - -def sample_list_node_pools(): - # Create a client - client = edgecontainer_v1.EdgeContainerClient() - - # Initialize request argument(s) - request = edgecontainer_v1.ListNodePoolsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_node_pools(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END edgecontainer_v1_generated_EdgeContainer_ListNodePools_sync] diff --git a/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_list_vpn_connections_async.py b/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_list_vpn_connections_async.py deleted file mode 100644 index 6f3eb9931bbf..000000000000 --- a/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_list_vpn_connections_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 ListVpnConnections -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-edgecontainer - - -# [START edgecontainer_v1_generated_EdgeContainer_ListVpnConnections_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 edgecontainer_v1 - - -async def sample_list_vpn_connections(): - # Create a client - client = edgecontainer_v1.EdgeContainerAsyncClient() - - # Initialize request argument(s) - request = edgecontainer_v1.ListVpnConnectionsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_vpn_connections(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END edgecontainer_v1_generated_EdgeContainer_ListVpnConnections_async] diff --git a/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_list_vpn_connections_sync.py b/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_list_vpn_connections_sync.py deleted file mode 100644 index dc6f1672e576..000000000000 --- a/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_list_vpn_connections_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 ListVpnConnections -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-edgecontainer - - -# [START edgecontainer_v1_generated_EdgeContainer_ListVpnConnections_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 edgecontainer_v1 - - -def sample_list_vpn_connections(): - # Create a client - client = edgecontainer_v1.EdgeContainerClient() - - # Initialize request argument(s) - request = edgecontainer_v1.ListVpnConnectionsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_vpn_connections(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END edgecontainer_v1_generated_EdgeContainer_ListVpnConnections_sync] diff --git a/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_update_cluster_async.py b/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_update_cluster_async.py deleted file mode 100644 index 17b6e2a01217..000000000000 --- a/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_update_cluster_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 UpdateCluster -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-edgecontainer - - -# [START edgecontainer_v1_generated_EdgeContainer_UpdateCluster_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 edgecontainer_v1 - - -async def sample_update_cluster(): - # Create a client - client = edgecontainer_v1.EdgeContainerAsyncClient() - - # Initialize request argument(s) - request = edgecontainer_v1.UpdateClusterRequest( - ) - - # Make the request - operation = client.update_cluster(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END edgecontainer_v1_generated_EdgeContainer_UpdateCluster_async] diff --git a/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_update_cluster_sync.py b/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_update_cluster_sync.py deleted file mode 100644 index 875ffe78c277..000000000000 --- a/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_update_cluster_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 UpdateCluster -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-edgecontainer - - -# [START edgecontainer_v1_generated_EdgeContainer_UpdateCluster_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 edgecontainer_v1 - - -def sample_update_cluster(): - # Create a client - client = edgecontainer_v1.EdgeContainerClient() - - # Initialize request argument(s) - request = edgecontainer_v1.UpdateClusterRequest( - ) - - # Make the request - operation = client.update_cluster(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END edgecontainer_v1_generated_EdgeContainer_UpdateCluster_sync] diff --git a/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_update_node_pool_async.py b/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_update_node_pool_async.py deleted file mode 100644 index 31e44b530596..000000000000 --- a/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_update_node_pool_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 UpdateNodePool -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-edgecontainer - - -# [START edgecontainer_v1_generated_EdgeContainer_UpdateNodePool_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 edgecontainer_v1 - - -async def sample_update_node_pool(): - # Create a client - client = edgecontainer_v1.EdgeContainerAsyncClient() - - # Initialize request argument(s) - request = edgecontainer_v1.UpdateNodePoolRequest( - ) - - # Make the request - operation = client.update_node_pool(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END edgecontainer_v1_generated_EdgeContainer_UpdateNodePool_async] diff --git a/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_update_node_pool_sync.py b/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_update_node_pool_sync.py deleted file mode 100644 index 6b21c7dd2b61..000000000000 --- a/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_update_node_pool_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 UpdateNodePool -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-edgecontainer - - -# [START edgecontainer_v1_generated_EdgeContainer_UpdateNodePool_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 edgecontainer_v1 - - -def sample_update_node_pool(): - # Create a client - client = edgecontainer_v1.EdgeContainerClient() - - # Initialize request argument(s) - request = edgecontainer_v1.UpdateNodePoolRequest( - ) - - # Make the request - operation = client.update_node_pool(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END edgecontainer_v1_generated_EdgeContainer_UpdateNodePool_sync] diff --git a/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_upgrade_cluster_async.py b/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_upgrade_cluster_async.py deleted file mode 100644 index c11313f85075..000000000000 --- a/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_upgrade_cluster_async.py +++ /dev/null @@ -1,57 +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 UpgradeCluster -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-edgecontainer - - -# [START edgecontainer_v1_generated_EdgeContainer_UpgradeCluster_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 edgecontainer_v1 - - -async def sample_upgrade_cluster(): - # Create a client - client = edgecontainer_v1.EdgeContainerAsyncClient() - - # Initialize request argument(s) - request = edgecontainer_v1.UpgradeClusterRequest( - name="name_value", - target_version="target_version_value", - ) - - # Make the request - operation = client.upgrade_cluster(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END edgecontainer_v1_generated_EdgeContainer_UpgradeCluster_async] diff --git a/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_upgrade_cluster_sync.py b/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_upgrade_cluster_sync.py deleted file mode 100644 index 39ee0ff4e5c2..000000000000 --- a/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/edgecontainer_v1_generated_edge_container_upgrade_cluster_sync.py +++ /dev/null @@ -1,57 +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 UpgradeCluster -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-edgecontainer - - -# [START edgecontainer_v1_generated_EdgeContainer_UpgradeCluster_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 edgecontainer_v1 - - -def sample_upgrade_cluster(): - # Create a client - client = edgecontainer_v1.EdgeContainerClient() - - # Initialize request argument(s) - request = edgecontainer_v1.UpgradeClusterRequest( - name="name_value", - target_version="target_version_value", - ) - - # Make the request - operation = client.upgrade_cluster(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END edgecontainer_v1_generated_EdgeContainer_UpgradeCluster_sync] diff --git a/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/snippet_metadata_google.cloud.edgecontainer.v1.json b/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/snippet_metadata_google.cloud.edgecontainer.v1.json deleted file mode 100644 index 3cd9098ed4e2..000000000000 --- a/owl-bot-staging/google-cloud-edgecontainer/v1/samples/generated_samples/snippet_metadata_google.cloud.edgecontainer.v1.json +++ /dev/null @@ -1,3315 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.cloud.edgecontainer.v1", - "version": "v1" - } - ], - "language": "PYTHON", - "name": "google-cloud-edgecontainer", - "version": "0.1.0" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.edgecontainer_v1.EdgeContainerAsyncClient", - "shortName": "EdgeContainerAsyncClient" - }, - "fullName": "google.cloud.edgecontainer_v1.EdgeContainerAsyncClient.create_cluster", - "method": { - "fullName": "google.cloud.edgecontainer.v1.EdgeContainer.CreateCluster", - "service": { - "fullName": "google.cloud.edgecontainer.v1.EdgeContainer", - "shortName": "EdgeContainer" - }, - "shortName": "CreateCluster" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.edgecontainer_v1.types.CreateClusterRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "cluster", - "type": "google.cloud.edgecontainer_v1.types.Cluster" - }, - { - "name": "cluster_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_cluster" - }, - "description": "Sample for CreateCluster", - "file": "edgecontainer_v1_generated_edge_container_create_cluster_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "edgecontainer_v1_generated_EdgeContainer_CreateCluster_async", - "segments": [ - { - "end": 64, - "start": 27, - "type": "FULL" - }, - { - "end": 64, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 54, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 61, - "start": 55, - "type": "REQUEST_EXECUTION" - }, - { - "end": 65, - "start": 62, - "type": "RESPONSE_HANDLING" - } - ], - "title": "edgecontainer_v1_generated_edge_container_create_cluster_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.edgecontainer_v1.EdgeContainerClient", - "shortName": "EdgeContainerClient" - }, - "fullName": "google.cloud.edgecontainer_v1.EdgeContainerClient.create_cluster", - "method": { - "fullName": "google.cloud.edgecontainer.v1.EdgeContainer.CreateCluster", - "service": { - "fullName": "google.cloud.edgecontainer.v1.EdgeContainer", - "shortName": "EdgeContainer" - }, - "shortName": "CreateCluster" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.edgecontainer_v1.types.CreateClusterRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "cluster", - "type": "google.cloud.edgecontainer_v1.types.Cluster" - }, - { - "name": "cluster_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "create_cluster" - }, - "description": "Sample for CreateCluster", - "file": "edgecontainer_v1_generated_edge_container_create_cluster_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "edgecontainer_v1_generated_EdgeContainer_CreateCluster_sync", - "segments": [ - { - "end": 64, - "start": 27, - "type": "FULL" - }, - { - "end": 64, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 54, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 61, - "start": 55, - "type": "REQUEST_EXECUTION" - }, - { - "end": 65, - "start": 62, - "type": "RESPONSE_HANDLING" - } - ], - "title": "edgecontainer_v1_generated_edge_container_create_cluster_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.edgecontainer_v1.EdgeContainerAsyncClient", - "shortName": "EdgeContainerAsyncClient" - }, - "fullName": "google.cloud.edgecontainer_v1.EdgeContainerAsyncClient.create_node_pool", - "method": { - "fullName": "google.cloud.edgecontainer.v1.EdgeContainer.CreateNodePool", - "service": { - "fullName": "google.cloud.edgecontainer.v1.EdgeContainer", - "shortName": "EdgeContainer" - }, - "shortName": "CreateNodePool" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.edgecontainer_v1.types.CreateNodePoolRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "node_pool", - "type": "google.cloud.edgecontainer_v1.types.NodePool" - }, - { - "name": "node_pool_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_node_pool" - }, - "description": "Sample for CreateNodePool", - "file": "edgecontainer_v1_generated_edge_container_create_node_pool_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "edgecontainer_v1_generated_EdgeContainer_CreateNodePool_async", - "segments": [ - { - "end": 61, - "start": 27, - "type": "FULL" - }, - { - "end": 61, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 51, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 58, - "start": 52, - "type": "REQUEST_EXECUTION" - }, - { - "end": 62, - "start": 59, - "type": "RESPONSE_HANDLING" - } - ], - "title": "edgecontainer_v1_generated_edge_container_create_node_pool_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.edgecontainer_v1.EdgeContainerClient", - "shortName": "EdgeContainerClient" - }, - "fullName": "google.cloud.edgecontainer_v1.EdgeContainerClient.create_node_pool", - "method": { - "fullName": "google.cloud.edgecontainer.v1.EdgeContainer.CreateNodePool", - "service": { - "fullName": "google.cloud.edgecontainer.v1.EdgeContainer", - "shortName": "EdgeContainer" - }, - "shortName": "CreateNodePool" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.edgecontainer_v1.types.CreateNodePoolRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "node_pool", - "type": "google.cloud.edgecontainer_v1.types.NodePool" - }, - { - "name": "node_pool_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "create_node_pool" - }, - "description": "Sample for CreateNodePool", - "file": "edgecontainer_v1_generated_edge_container_create_node_pool_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "edgecontainer_v1_generated_EdgeContainer_CreateNodePool_sync", - "segments": [ - { - "end": 61, - "start": 27, - "type": "FULL" - }, - { - "end": 61, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 51, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 58, - "start": 52, - "type": "REQUEST_EXECUTION" - }, - { - "end": 62, - "start": 59, - "type": "RESPONSE_HANDLING" - } - ], - "title": "edgecontainer_v1_generated_edge_container_create_node_pool_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.edgecontainer_v1.EdgeContainerAsyncClient", - "shortName": "EdgeContainerAsyncClient" - }, - "fullName": "google.cloud.edgecontainer_v1.EdgeContainerAsyncClient.create_vpn_connection", - "method": { - "fullName": "google.cloud.edgecontainer.v1.EdgeContainer.CreateVpnConnection", - "service": { - "fullName": "google.cloud.edgecontainer.v1.EdgeContainer", - "shortName": "EdgeContainer" - }, - "shortName": "CreateVpnConnection" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.edgecontainer_v1.types.CreateVpnConnectionRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "vpn_connection", - "type": "google.cloud.edgecontainer_v1.types.VpnConnection" - }, - { - "name": "vpn_connection_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_vpn_connection" - }, - "description": "Sample for CreateVpnConnection", - "file": "edgecontainer_v1_generated_edge_container_create_vpn_connection_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "edgecontainer_v1_generated_EdgeContainer_CreateVpnConnection_async", - "segments": [ - { - "end": 60, - "start": 27, - "type": "FULL" - }, - { - "end": 60, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 50, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 57, - "start": 51, - "type": "REQUEST_EXECUTION" - }, - { - "end": 61, - "start": 58, - "type": "RESPONSE_HANDLING" - } - ], - "title": "edgecontainer_v1_generated_edge_container_create_vpn_connection_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.edgecontainer_v1.EdgeContainerClient", - "shortName": "EdgeContainerClient" - }, - "fullName": "google.cloud.edgecontainer_v1.EdgeContainerClient.create_vpn_connection", - "method": { - "fullName": "google.cloud.edgecontainer.v1.EdgeContainer.CreateVpnConnection", - "service": { - "fullName": "google.cloud.edgecontainer.v1.EdgeContainer", - "shortName": "EdgeContainer" - }, - "shortName": "CreateVpnConnection" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.edgecontainer_v1.types.CreateVpnConnectionRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "vpn_connection", - "type": "google.cloud.edgecontainer_v1.types.VpnConnection" - }, - { - "name": "vpn_connection_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "create_vpn_connection" - }, - "description": "Sample for CreateVpnConnection", - "file": "edgecontainer_v1_generated_edge_container_create_vpn_connection_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "edgecontainer_v1_generated_EdgeContainer_CreateVpnConnection_sync", - "segments": [ - { - "end": 60, - "start": 27, - "type": "FULL" - }, - { - "end": 60, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 50, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 57, - "start": 51, - "type": "REQUEST_EXECUTION" - }, - { - "end": 61, - "start": 58, - "type": "RESPONSE_HANDLING" - } - ], - "title": "edgecontainer_v1_generated_edge_container_create_vpn_connection_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.edgecontainer_v1.EdgeContainerAsyncClient", - "shortName": "EdgeContainerAsyncClient" - }, - "fullName": "google.cloud.edgecontainer_v1.EdgeContainerAsyncClient.delete_cluster", - "method": { - "fullName": "google.cloud.edgecontainer.v1.EdgeContainer.DeleteCluster", - "service": { - "fullName": "google.cloud.edgecontainer.v1.EdgeContainer", - "shortName": "EdgeContainer" - }, - "shortName": "DeleteCluster" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.edgecontainer_v1.types.DeleteClusterRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_cluster" - }, - "description": "Sample for DeleteCluster", - "file": "edgecontainer_v1_generated_edge_container_delete_cluster_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "edgecontainer_v1_generated_EdgeContainer_DeleteCluster_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": "edgecontainer_v1_generated_edge_container_delete_cluster_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.edgecontainer_v1.EdgeContainerClient", - "shortName": "EdgeContainerClient" - }, - "fullName": "google.cloud.edgecontainer_v1.EdgeContainerClient.delete_cluster", - "method": { - "fullName": "google.cloud.edgecontainer.v1.EdgeContainer.DeleteCluster", - "service": { - "fullName": "google.cloud.edgecontainer.v1.EdgeContainer", - "shortName": "EdgeContainer" - }, - "shortName": "DeleteCluster" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.edgecontainer_v1.types.DeleteClusterRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "delete_cluster" - }, - "description": "Sample for DeleteCluster", - "file": "edgecontainer_v1_generated_edge_container_delete_cluster_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "edgecontainer_v1_generated_EdgeContainer_DeleteCluster_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": "edgecontainer_v1_generated_edge_container_delete_cluster_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.edgecontainer_v1.EdgeContainerAsyncClient", - "shortName": "EdgeContainerAsyncClient" - }, - "fullName": "google.cloud.edgecontainer_v1.EdgeContainerAsyncClient.delete_node_pool", - "method": { - "fullName": "google.cloud.edgecontainer.v1.EdgeContainer.DeleteNodePool", - "service": { - "fullName": "google.cloud.edgecontainer.v1.EdgeContainer", - "shortName": "EdgeContainer" - }, - "shortName": "DeleteNodePool" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.edgecontainer_v1.types.DeleteNodePoolRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_node_pool" - }, - "description": "Sample for DeleteNodePool", - "file": "edgecontainer_v1_generated_edge_container_delete_node_pool_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "edgecontainer_v1_generated_EdgeContainer_DeleteNodePool_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": "edgecontainer_v1_generated_edge_container_delete_node_pool_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.edgecontainer_v1.EdgeContainerClient", - "shortName": "EdgeContainerClient" - }, - "fullName": "google.cloud.edgecontainer_v1.EdgeContainerClient.delete_node_pool", - "method": { - "fullName": "google.cloud.edgecontainer.v1.EdgeContainer.DeleteNodePool", - "service": { - "fullName": "google.cloud.edgecontainer.v1.EdgeContainer", - "shortName": "EdgeContainer" - }, - "shortName": "DeleteNodePool" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.edgecontainer_v1.types.DeleteNodePoolRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "delete_node_pool" - }, - "description": "Sample for DeleteNodePool", - "file": "edgecontainer_v1_generated_edge_container_delete_node_pool_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "edgecontainer_v1_generated_EdgeContainer_DeleteNodePool_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": "edgecontainer_v1_generated_edge_container_delete_node_pool_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.edgecontainer_v1.EdgeContainerAsyncClient", - "shortName": "EdgeContainerAsyncClient" - }, - "fullName": "google.cloud.edgecontainer_v1.EdgeContainerAsyncClient.delete_vpn_connection", - "method": { - "fullName": "google.cloud.edgecontainer.v1.EdgeContainer.DeleteVpnConnection", - "service": { - "fullName": "google.cloud.edgecontainer.v1.EdgeContainer", - "shortName": "EdgeContainer" - }, - "shortName": "DeleteVpnConnection" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.edgecontainer_v1.types.DeleteVpnConnectionRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_vpn_connection" - }, - "description": "Sample for DeleteVpnConnection", - "file": "edgecontainer_v1_generated_edge_container_delete_vpn_connection_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "edgecontainer_v1_generated_EdgeContainer_DeleteVpnConnection_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": "edgecontainer_v1_generated_edge_container_delete_vpn_connection_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.edgecontainer_v1.EdgeContainerClient", - "shortName": "EdgeContainerClient" - }, - "fullName": "google.cloud.edgecontainer_v1.EdgeContainerClient.delete_vpn_connection", - "method": { - "fullName": "google.cloud.edgecontainer.v1.EdgeContainer.DeleteVpnConnection", - "service": { - "fullName": "google.cloud.edgecontainer.v1.EdgeContainer", - "shortName": "EdgeContainer" - }, - "shortName": "DeleteVpnConnection" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.edgecontainer_v1.types.DeleteVpnConnectionRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "delete_vpn_connection" - }, - "description": "Sample for DeleteVpnConnection", - "file": "edgecontainer_v1_generated_edge_container_delete_vpn_connection_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "edgecontainer_v1_generated_EdgeContainer_DeleteVpnConnection_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": "edgecontainer_v1_generated_edge_container_delete_vpn_connection_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.edgecontainer_v1.EdgeContainerAsyncClient", - "shortName": "EdgeContainerAsyncClient" - }, - "fullName": "google.cloud.edgecontainer_v1.EdgeContainerAsyncClient.generate_access_token", - "method": { - "fullName": "google.cloud.edgecontainer.v1.EdgeContainer.GenerateAccessToken", - "service": { - "fullName": "google.cloud.edgecontainer.v1.EdgeContainer", - "shortName": "EdgeContainer" - }, - "shortName": "GenerateAccessToken" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.edgecontainer_v1.types.GenerateAccessTokenRequest" - }, - { - "name": "cluster", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.edgecontainer_v1.types.GenerateAccessTokenResponse", - "shortName": "generate_access_token" - }, - "description": "Sample for GenerateAccessToken", - "file": "edgecontainer_v1_generated_edge_container_generate_access_token_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "edgecontainer_v1_generated_EdgeContainer_GenerateAccessToken_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": "edgecontainer_v1_generated_edge_container_generate_access_token_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.edgecontainer_v1.EdgeContainerClient", - "shortName": "EdgeContainerClient" - }, - "fullName": "google.cloud.edgecontainer_v1.EdgeContainerClient.generate_access_token", - "method": { - "fullName": "google.cloud.edgecontainer.v1.EdgeContainer.GenerateAccessToken", - "service": { - "fullName": "google.cloud.edgecontainer.v1.EdgeContainer", - "shortName": "EdgeContainer" - }, - "shortName": "GenerateAccessToken" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.edgecontainer_v1.types.GenerateAccessTokenRequest" - }, - { - "name": "cluster", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.edgecontainer_v1.types.GenerateAccessTokenResponse", - "shortName": "generate_access_token" - }, - "description": "Sample for GenerateAccessToken", - "file": "edgecontainer_v1_generated_edge_container_generate_access_token_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "edgecontainer_v1_generated_EdgeContainer_GenerateAccessToken_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": "edgecontainer_v1_generated_edge_container_generate_access_token_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.edgecontainer_v1.EdgeContainerAsyncClient", - "shortName": "EdgeContainerAsyncClient" - }, - "fullName": "google.cloud.edgecontainer_v1.EdgeContainerAsyncClient.generate_offline_credential", - "method": { - "fullName": "google.cloud.edgecontainer.v1.EdgeContainer.GenerateOfflineCredential", - "service": { - "fullName": "google.cloud.edgecontainer.v1.EdgeContainer", - "shortName": "EdgeContainer" - }, - "shortName": "GenerateOfflineCredential" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.edgecontainer_v1.types.GenerateOfflineCredentialRequest" - }, - { - "name": "cluster", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.edgecontainer_v1.types.GenerateOfflineCredentialResponse", - "shortName": "generate_offline_credential" - }, - "description": "Sample for GenerateOfflineCredential", - "file": "edgecontainer_v1_generated_edge_container_generate_offline_credential_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "edgecontainer_v1_generated_EdgeContainer_GenerateOfflineCredential_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": "edgecontainer_v1_generated_edge_container_generate_offline_credential_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.edgecontainer_v1.EdgeContainerClient", - "shortName": "EdgeContainerClient" - }, - "fullName": "google.cloud.edgecontainer_v1.EdgeContainerClient.generate_offline_credential", - "method": { - "fullName": "google.cloud.edgecontainer.v1.EdgeContainer.GenerateOfflineCredential", - "service": { - "fullName": "google.cloud.edgecontainer.v1.EdgeContainer", - "shortName": "EdgeContainer" - }, - "shortName": "GenerateOfflineCredential" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.edgecontainer_v1.types.GenerateOfflineCredentialRequest" - }, - { - "name": "cluster", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.edgecontainer_v1.types.GenerateOfflineCredentialResponse", - "shortName": "generate_offline_credential" - }, - "description": "Sample for GenerateOfflineCredential", - "file": "edgecontainer_v1_generated_edge_container_generate_offline_credential_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "edgecontainer_v1_generated_EdgeContainer_GenerateOfflineCredential_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": "edgecontainer_v1_generated_edge_container_generate_offline_credential_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.edgecontainer_v1.EdgeContainerAsyncClient", - "shortName": "EdgeContainerAsyncClient" - }, - "fullName": "google.cloud.edgecontainer_v1.EdgeContainerAsyncClient.get_cluster", - "method": { - "fullName": "google.cloud.edgecontainer.v1.EdgeContainer.GetCluster", - "service": { - "fullName": "google.cloud.edgecontainer.v1.EdgeContainer", - "shortName": "EdgeContainer" - }, - "shortName": "GetCluster" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.edgecontainer_v1.types.GetClusterRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.edgecontainer_v1.types.Cluster", - "shortName": "get_cluster" - }, - "description": "Sample for GetCluster", - "file": "edgecontainer_v1_generated_edge_container_get_cluster_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "edgecontainer_v1_generated_EdgeContainer_GetCluster_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": "edgecontainer_v1_generated_edge_container_get_cluster_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.edgecontainer_v1.EdgeContainerClient", - "shortName": "EdgeContainerClient" - }, - "fullName": "google.cloud.edgecontainer_v1.EdgeContainerClient.get_cluster", - "method": { - "fullName": "google.cloud.edgecontainer.v1.EdgeContainer.GetCluster", - "service": { - "fullName": "google.cloud.edgecontainer.v1.EdgeContainer", - "shortName": "EdgeContainer" - }, - "shortName": "GetCluster" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.edgecontainer_v1.types.GetClusterRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.edgecontainer_v1.types.Cluster", - "shortName": "get_cluster" - }, - "description": "Sample for GetCluster", - "file": "edgecontainer_v1_generated_edge_container_get_cluster_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "edgecontainer_v1_generated_EdgeContainer_GetCluster_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": "edgecontainer_v1_generated_edge_container_get_cluster_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.edgecontainer_v1.EdgeContainerAsyncClient", - "shortName": "EdgeContainerAsyncClient" - }, - "fullName": "google.cloud.edgecontainer_v1.EdgeContainerAsyncClient.get_machine", - "method": { - "fullName": "google.cloud.edgecontainer.v1.EdgeContainer.GetMachine", - "service": { - "fullName": "google.cloud.edgecontainer.v1.EdgeContainer", - "shortName": "EdgeContainer" - }, - "shortName": "GetMachine" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.edgecontainer_v1.types.GetMachineRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.edgecontainer_v1.types.Machine", - "shortName": "get_machine" - }, - "description": "Sample for GetMachine", - "file": "edgecontainer_v1_generated_edge_container_get_machine_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "edgecontainer_v1_generated_EdgeContainer_GetMachine_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": "edgecontainer_v1_generated_edge_container_get_machine_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.edgecontainer_v1.EdgeContainerClient", - "shortName": "EdgeContainerClient" - }, - "fullName": "google.cloud.edgecontainer_v1.EdgeContainerClient.get_machine", - "method": { - "fullName": "google.cloud.edgecontainer.v1.EdgeContainer.GetMachine", - "service": { - "fullName": "google.cloud.edgecontainer.v1.EdgeContainer", - "shortName": "EdgeContainer" - }, - "shortName": "GetMachine" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.edgecontainer_v1.types.GetMachineRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.edgecontainer_v1.types.Machine", - "shortName": "get_machine" - }, - "description": "Sample for GetMachine", - "file": "edgecontainer_v1_generated_edge_container_get_machine_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "edgecontainer_v1_generated_EdgeContainer_GetMachine_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": "edgecontainer_v1_generated_edge_container_get_machine_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.edgecontainer_v1.EdgeContainerAsyncClient", - "shortName": "EdgeContainerAsyncClient" - }, - "fullName": "google.cloud.edgecontainer_v1.EdgeContainerAsyncClient.get_node_pool", - "method": { - "fullName": "google.cloud.edgecontainer.v1.EdgeContainer.GetNodePool", - "service": { - "fullName": "google.cloud.edgecontainer.v1.EdgeContainer", - "shortName": "EdgeContainer" - }, - "shortName": "GetNodePool" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.edgecontainer_v1.types.GetNodePoolRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.edgecontainer_v1.types.NodePool", - "shortName": "get_node_pool" - }, - "description": "Sample for GetNodePool", - "file": "edgecontainer_v1_generated_edge_container_get_node_pool_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "edgecontainer_v1_generated_EdgeContainer_GetNodePool_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": "edgecontainer_v1_generated_edge_container_get_node_pool_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.edgecontainer_v1.EdgeContainerClient", - "shortName": "EdgeContainerClient" - }, - "fullName": "google.cloud.edgecontainer_v1.EdgeContainerClient.get_node_pool", - "method": { - "fullName": "google.cloud.edgecontainer.v1.EdgeContainer.GetNodePool", - "service": { - "fullName": "google.cloud.edgecontainer.v1.EdgeContainer", - "shortName": "EdgeContainer" - }, - "shortName": "GetNodePool" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.edgecontainer_v1.types.GetNodePoolRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.edgecontainer_v1.types.NodePool", - "shortName": "get_node_pool" - }, - "description": "Sample for GetNodePool", - "file": "edgecontainer_v1_generated_edge_container_get_node_pool_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "edgecontainer_v1_generated_EdgeContainer_GetNodePool_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": "edgecontainer_v1_generated_edge_container_get_node_pool_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.edgecontainer_v1.EdgeContainerAsyncClient", - "shortName": "EdgeContainerAsyncClient" - }, - "fullName": "google.cloud.edgecontainer_v1.EdgeContainerAsyncClient.get_server_config", - "method": { - "fullName": "google.cloud.edgecontainer.v1.EdgeContainer.GetServerConfig", - "service": { - "fullName": "google.cloud.edgecontainer.v1.EdgeContainer", - "shortName": "EdgeContainer" - }, - "shortName": "GetServerConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.edgecontainer_v1.types.GetServerConfigRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.edgecontainer_v1.types.ServerConfig", - "shortName": "get_server_config" - }, - "description": "Sample for GetServerConfig", - "file": "edgecontainer_v1_generated_edge_container_get_server_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "edgecontainer_v1_generated_EdgeContainer_GetServerConfig_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": "edgecontainer_v1_generated_edge_container_get_server_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.edgecontainer_v1.EdgeContainerClient", - "shortName": "EdgeContainerClient" - }, - "fullName": "google.cloud.edgecontainer_v1.EdgeContainerClient.get_server_config", - "method": { - "fullName": "google.cloud.edgecontainer.v1.EdgeContainer.GetServerConfig", - "service": { - "fullName": "google.cloud.edgecontainer.v1.EdgeContainer", - "shortName": "EdgeContainer" - }, - "shortName": "GetServerConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.edgecontainer_v1.types.GetServerConfigRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.edgecontainer_v1.types.ServerConfig", - "shortName": "get_server_config" - }, - "description": "Sample for GetServerConfig", - "file": "edgecontainer_v1_generated_edge_container_get_server_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "edgecontainer_v1_generated_EdgeContainer_GetServerConfig_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": "edgecontainer_v1_generated_edge_container_get_server_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.edgecontainer_v1.EdgeContainerAsyncClient", - "shortName": "EdgeContainerAsyncClient" - }, - "fullName": "google.cloud.edgecontainer_v1.EdgeContainerAsyncClient.get_vpn_connection", - "method": { - "fullName": "google.cloud.edgecontainer.v1.EdgeContainer.GetVpnConnection", - "service": { - "fullName": "google.cloud.edgecontainer.v1.EdgeContainer", - "shortName": "EdgeContainer" - }, - "shortName": "GetVpnConnection" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.edgecontainer_v1.types.GetVpnConnectionRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.edgecontainer_v1.types.VpnConnection", - "shortName": "get_vpn_connection" - }, - "description": "Sample for GetVpnConnection", - "file": "edgecontainer_v1_generated_edge_container_get_vpn_connection_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "edgecontainer_v1_generated_EdgeContainer_GetVpnConnection_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": "edgecontainer_v1_generated_edge_container_get_vpn_connection_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.edgecontainer_v1.EdgeContainerClient", - "shortName": "EdgeContainerClient" - }, - "fullName": "google.cloud.edgecontainer_v1.EdgeContainerClient.get_vpn_connection", - "method": { - "fullName": "google.cloud.edgecontainer.v1.EdgeContainer.GetVpnConnection", - "service": { - "fullName": "google.cloud.edgecontainer.v1.EdgeContainer", - "shortName": "EdgeContainer" - }, - "shortName": "GetVpnConnection" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.edgecontainer_v1.types.GetVpnConnectionRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.edgecontainer_v1.types.VpnConnection", - "shortName": "get_vpn_connection" - }, - "description": "Sample for GetVpnConnection", - "file": "edgecontainer_v1_generated_edge_container_get_vpn_connection_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "edgecontainer_v1_generated_EdgeContainer_GetVpnConnection_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": "edgecontainer_v1_generated_edge_container_get_vpn_connection_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.edgecontainer_v1.EdgeContainerAsyncClient", - "shortName": "EdgeContainerAsyncClient" - }, - "fullName": "google.cloud.edgecontainer_v1.EdgeContainerAsyncClient.list_clusters", - "method": { - "fullName": "google.cloud.edgecontainer.v1.EdgeContainer.ListClusters", - "service": { - "fullName": "google.cloud.edgecontainer.v1.EdgeContainer", - "shortName": "EdgeContainer" - }, - "shortName": "ListClusters" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.edgecontainer_v1.types.ListClustersRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.edgecontainer_v1.services.edge_container.pagers.ListClustersAsyncPager", - "shortName": "list_clusters" - }, - "description": "Sample for ListClusters", - "file": "edgecontainer_v1_generated_edge_container_list_clusters_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "edgecontainer_v1_generated_EdgeContainer_ListClusters_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": "edgecontainer_v1_generated_edge_container_list_clusters_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.edgecontainer_v1.EdgeContainerClient", - "shortName": "EdgeContainerClient" - }, - "fullName": "google.cloud.edgecontainer_v1.EdgeContainerClient.list_clusters", - "method": { - "fullName": "google.cloud.edgecontainer.v1.EdgeContainer.ListClusters", - "service": { - "fullName": "google.cloud.edgecontainer.v1.EdgeContainer", - "shortName": "EdgeContainer" - }, - "shortName": "ListClusters" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.edgecontainer_v1.types.ListClustersRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.edgecontainer_v1.services.edge_container.pagers.ListClustersPager", - "shortName": "list_clusters" - }, - "description": "Sample for ListClusters", - "file": "edgecontainer_v1_generated_edge_container_list_clusters_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "edgecontainer_v1_generated_EdgeContainer_ListClusters_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": "edgecontainer_v1_generated_edge_container_list_clusters_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.edgecontainer_v1.EdgeContainerAsyncClient", - "shortName": "EdgeContainerAsyncClient" - }, - "fullName": "google.cloud.edgecontainer_v1.EdgeContainerAsyncClient.list_machines", - "method": { - "fullName": "google.cloud.edgecontainer.v1.EdgeContainer.ListMachines", - "service": { - "fullName": "google.cloud.edgecontainer.v1.EdgeContainer", - "shortName": "EdgeContainer" - }, - "shortName": "ListMachines" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.edgecontainer_v1.types.ListMachinesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.edgecontainer_v1.services.edge_container.pagers.ListMachinesAsyncPager", - "shortName": "list_machines" - }, - "description": "Sample for ListMachines", - "file": "edgecontainer_v1_generated_edge_container_list_machines_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "edgecontainer_v1_generated_EdgeContainer_ListMachines_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": "edgecontainer_v1_generated_edge_container_list_machines_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.edgecontainer_v1.EdgeContainerClient", - "shortName": "EdgeContainerClient" - }, - "fullName": "google.cloud.edgecontainer_v1.EdgeContainerClient.list_machines", - "method": { - "fullName": "google.cloud.edgecontainer.v1.EdgeContainer.ListMachines", - "service": { - "fullName": "google.cloud.edgecontainer.v1.EdgeContainer", - "shortName": "EdgeContainer" - }, - "shortName": "ListMachines" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.edgecontainer_v1.types.ListMachinesRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.edgecontainer_v1.services.edge_container.pagers.ListMachinesPager", - "shortName": "list_machines" - }, - "description": "Sample for ListMachines", - "file": "edgecontainer_v1_generated_edge_container_list_machines_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "edgecontainer_v1_generated_EdgeContainer_ListMachines_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": "edgecontainer_v1_generated_edge_container_list_machines_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.edgecontainer_v1.EdgeContainerAsyncClient", - "shortName": "EdgeContainerAsyncClient" - }, - "fullName": "google.cloud.edgecontainer_v1.EdgeContainerAsyncClient.list_node_pools", - "method": { - "fullName": "google.cloud.edgecontainer.v1.EdgeContainer.ListNodePools", - "service": { - "fullName": "google.cloud.edgecontainer.v1.EdgeContainer", - "shortName": "EdgeContainer" - }, - "shortName": "ListNodePools" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.edgecontainer_v1.types.ListNodePoolsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.edgecontainer_v1.services.edge_container.pagers.ListNodePoolsAsyncPager", - "shortName": "list_node_pools" - }, - "description": "Sample for ListNodePools", - "file": "edgecontainer_v1_generated_edge_container_list_node_pools_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "edgecontainer_v1_generated_EdgeContainer_ListNodePools_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": "edgecontainer_v1_generated_edge_container_list_node_pools_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.edgecontainer_v1.EdgeContainerClient", - "shortName": "EdgeContainerClient" - }, - "fullName": "google.cloud.edgecontainer_v1.EdgeContainerClient.list_node_pools", - "method": { - "fullName": "google.cloud.edgecontainer.v1.EdgeContainer.ListNodePools", - "service": { - "fullName": "google.cloud.edgecontainer.v1.EdgeContainer", - "shortName": "EdgeContainer" - }, - "shortName": "ListNodePools" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.edgecontainer_v1.types.ListNodePoolsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.edgecontainer_v1.services.edge_container.pagers.ListNodePoolsPager", - "shortName": "list_node_pools" - }, - "description": "Sample for ListNodePools", - "file": "edgecontainer_v1_generated_edge_container_list_node_pools_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "edgecontainer_v1_generated_EdgeContainer_ListNodePools_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": "edgecontainer_v1_generated_edge_container_list_node_pools_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.edgecontainer_v1.EdgeContainerAsyncClient", - "shortName": "EdgeContainerAsyncClient" - }, - "fullName": "google.cloud.edgecontainer_v1.EdgeContainerAsyncClient.list_vpn_connections", - "method": { - "fullName": "google.cloud.edgecontainer.v1.EdgeContainer.ListVpnConnections", - "service": { - "fullName": "google.cloud.edgecontainer.v1.EdgeContainer", - "shortName": "EdgeContainer" - }, - "shortName": "ListVpnConnections" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.edgecontainer_v1.types.ListVpnConnectionsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.edgecontainer_v1.services.edge_container.pagers.ListVpnConnectionsAsyncPager", - "shortName": "list_vpn_connections" - }, - "description": "Sample for ListVpnConnections", - "file": "edgecontainer_v1_generated_edge_container_list_vpn_connections_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "edgecontainer_v1_generated_EdgeContainer_ListVpnConnections_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": "edgecontainer_v1_generated_edge_container_list_vpn_connections_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.edgecontainer_v1.EdgeContainerClient", - "shortName": "EdgeContainerClient" - }, - "fullName": "google.cloud.edgecontainer_v1.EdgeContainerClient.list_vpn_connections", - "method": { - "fullName": "google.cloud.edgecontainer.v1.EdgeContainer.ListVpnConnections", - "service": { - "fullName": "google.cloud.edgecontainer.v1.EdgeContainer", - "shortName": "EdgeContainer" - }, - "shortName": "ListVpnConnections" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.edgecontainer_v1.types.ListVpnConnectionsRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.edgecontainer_v1.services.edge_container.pagers.ListVpnConnectionsPager", - "shortName": "list_vpn_connections" - }, - "description": "Sample for ListVpnConnections", - "file": "edgecontainer_v1_generated_edge_container_list_vpn_connections_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "edgecontainer_v1_generated_EdgeContainer_ListVpnConnections_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": "edgecontainer_v1_generated_edge_container_list_vpn_connections_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.edgecontainer_v1.EdgeContainerAsyncClient", - "shortName": "EdgeContainerAsyncClient" - }, - "fullName": "google.cloud.edgecontainer_v1.EdgeContainerAsyncClient.update_cluster", - "method": { - "fullName": "google.cloud.edgecontainer.v1.EdgeContainer.UpdateCluster", - "service": { - "fullName": "google.cloud.edgecontainer.v1.EdgeContainer", - "shortName": "EdgeContainer" - }, - "shortName": "UpdateCluster" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.edgecontainer_v1.types.UpdateClusterRequest" - }, - { - "name": "cluster", - "type": "google.cloud.edgecontainer_v1.types.Cluster" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "update_cluster" - }, - "description": "Sample for UpdateCluster", - "file": "edgecontainer_v1_generated_edge_container_update_cluster_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "edgecontainer_v1_generated_EdgeContainer_UpdateCluster_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": "edgecontainer_v1_generated_edge_container_update_cluster_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.edgecontainer_v1.EdgeContainerClient", - "shortName": "EdgeContainerClient" - }, - "fullName": "google.cloud.edgecontainer_v1.EdgeContainerClient.update_cluster", - "method": { - "fullName": "google.cloud.edgecontainer.v1.EdgeContainer.UpdateCluster", - "service": { - "fullName": "google.cloud.edgecontainer.v1.EdgeContainer", - "shortName": "EdgeContainer" - }, - "shortName": "UpdateCluster" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.edgecontainer_v1.types.UpdateClusterRequest" - }, - { - "name": "cluster", - "type": "google.cloud.edgecontainer_v1.types.Cluster" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "update_cluster" - }, - "description": "Sample for UpdateCluster", - "file": "edgecontainer_v1_generated_edge_container_update_cluster_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "edgecontainer_v1_generated_EdgeContainer_UpdateCluster_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": "edgecontainer_v1_generated_edge_container_update_cluster_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.edgecontainer_v1.EdgeContainerAsyncClient", - "shortName": "EdgeContainerAsyncClient" - }, - "fullName": "google.cloud.edgecontainer_v1.EdgeContainerAsyncClient.update_node_pool", - "method": { - "fullName": "google.cloud.edgecontainer.v1.EdgeContainer.UpdateNodePool", - "service": { - "fullName": "google.cloud.edgecontainer.v1.EdgeContainer", - "shortName": "EdgeContainer" - }, - "shortName": "UpdateNodePool" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.edgecontainer_v1.types.UpdateNodePoolRequest" - }, - { - "name": "node_pool", - "type": "google.cloud.edgecontainer_v1.types.NodePool" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "update_node_pool" - }, - "description": "Sample for UpdateNodePool", - "file": "edgecontainer_v1_generated_edge_container_update_node_pool_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "edgecontainer_v1_generated_EdgeContainer_UpdateNodePool_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": "edgecontainer_v1_generated_edge_container_update_node_pool_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.edgecontainer_v1.EdgeContainerClient", - "shortName": "EdgeContainerClient" - }, - "fullName": "google.cloud.edgecontainer_v1.EdgeContainerClient.update_node_pool", - "method": { - "fullName": "google.cloud.edgecontainer.v1.EdgeContainer.UpdateNodePool", - "service": { - "fullName": "google.cloud.edgecontainer.v1.EdgeContainer", - "shortName": "EdgeContainer" - }, - "shortName": "UpdateNodePool" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.edgecontainer_v1.types.UpdateNodePoolRequest" - }, - { - "name": "node_pool", - "type": "google.cloud.edgecontainer_v1.types.NodePool" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "update_node_pool" - }, - "description": "Sample for UpdateNodePool", - "file": "edgecontainer_v1_generated_edge_container_update_node_pool_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "edgecontainer_v1_generated_EdgeContainer_UpdateNodePool_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": "edgecontainer_v1_generated_edge_container_update_node_pool_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.edgecontainer_v1.EdgeContainerAsyncClient", - "shortName": "EdgeContainerAsyncClient" - }, - "fullName": "google.cloud.edgecontainer_v1.EdgeContainerAsyncClient.upgrade_cluster", - "method": { - "fullName": "google.cloud.edgecontainer.v1.EdgeContainer.UpgradeCluster", - "service": { - "fullName": "google.cloud.edgecontainer.v1.EdgeContainer", - "shortName": "EdgeContainer" - }, - "shortName": "UpgradeCluster" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.edgecontainer_v1.types.UpgradeClusterRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "target_version", - "type": "str" - }, - { - "name": "schedule", - "type": "google.cloud.edgecontainer_v1.types.UpgradeClusterRequest.Schedule" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "upgrade_cluster" - }, - "description": "Sample for UpgradeCluster", - "file": "edgecontainer_v1_generated_edge_container_upgrade_cluster_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "edgecontainer_v1_generated_EdgeContainer_UpgradeCluster_async", - "segments": [ - { - "end": 56, - "start": 27, - "type": "FULL" - }, - { - "end": 56, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 53, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 57, - "start": 54, - "type": "RESPONSE_HANDLING" - } - ], - "title": "edgecontainer_v1_generated_edge_container_upgrade_cluster_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.edgecontainer_v1.EdgeContainerClient", - "shortName": "EdgeContainerClient" - }, - "fullName": "google.cloud.edgecontainer_v1.EdgeContainerClient.upgrade_cluster", - "method": { - "fullName": "google.cloud.edgecontainer.v1.EdgeContainer.UpgradeCluster", - "service": { - "fullName": "google.cloud.edgecontainer.v1.EdgeContainer", - "shortName": "EdgeContainer" - }, - "shortName": "UpgradeCluster" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.edgecontainer_v1.types.UpgradeClusterRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "target_version", - "type": "str" - }, - { - "name": "schedule", - "type": "google.cloud.edgecontainer_v1.types.UpgradeClusterRequest.Schedule" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "upgrade_cluster" - }, - "description": "Sample for UpgradeCluster", - "file": "edgecontainer_v1_generated_edge_container_upgrade_cluster_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "edgecontainer_v1_generated_EdgeContainer_UpgradeCluster_sync", - "segments": [ - { - "end": 56, - "start": 27, - "type": "FULL" - }, - { - "end": 56, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 53, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 57, - "start": 54, - "type": "RESPONSE_HANDLING" - } - ], - "title": "edgecontainer_v1_generated_edge_container_upgrade_cluster_sync.py" - } - ] -} diff --git a/owl-bot-staging/google-cloud-edgecontainer/v1/scripts/fixup_edgecontainer_v1_keywords.py b/owl-bot-staging/google-cloud-edgecontainer/v1/scripts/fixup_edgecontainer_v1_keywords.py deleted file mode 100644 index 09a4a414eb52..000000000000 --- a/owl-bot-staging/google-cloud-edgecontainer/v1/scripts/fixup_edgecontainer_v1_keywords.py +++ /dev/null @@ -1,195 +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 edgecontainerCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'create_cluster': ('parent', 'cluster_id', 'cluster', 'request_id', ), - 'create_node_pool': ('parent', 'node_pool_id', 'node_pool', 'request_id', ), - 'create_vpn_connection': ('parent', 'vpn_connection_id', 'vpn_connection', 'request_id', ), - 'delete_cluster': ('name', 'request_id', ), - 'delete_node_pool': ('name', 'request_id', ), - 'delete_vpn_connection': ('name', 'request_id', ), - 'generate_access_token': ('cluster', ), - 'generate_offline_credential': ('cluster', ), - 'get_cluster': ('name', ), - 'get_machine': ('name', ), - 'get_node_pool': ('name', ), - 'get_server_config': ('name', ), - 'get_vpn_connection': ('name', ), - 'list_clusters': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), - 'list_machines': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), - 'list_node_pools': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), - 'list_vpn_connections': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), - 'update_cluster': ('update_mask', 'cluster', 'request_id', ), - 'update_node_pool': ('update_mask', 'node_pool', 'request_id', ), - 'upgrade_cluster': ('name', 'target_version', 'schedule', 'request_id', ), - } - - def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: - try: - key = original.func.attr.value - kword_params = self.METHOD_TO_PARAMS[key] - except (AttributeError, KeyError): - # Either not a method from the API or too convoluted to be sure. - return updated - - # If the existing code is valid, keyword args come after positional args. - # Therefore, all positional args must map to the first parameters. - args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) - if any(k.keyword.value == "request" for k in kwargs): - # We've already fixed this file, don't fix it again. - return updated - - kwargs, ctrl_kwargs = partition( - lambda a: a.keyword.value not in self.CTRL_PARAMS, - kwargs - ) - - args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] - ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) - for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) - - request_arg = cst.Arg( - value=cst.Dict([ - cst.DictElement( - cst.SimpleString("'{}'".format(name)), -cst.Element(value=arg.value) - ) - # Note: the args + kwargs looks silly, but keep in mind that - # the control parameters had to be stripped out, and that - # those could have been passed positionally or by keyword. - for name, arg in zip(kword_params, args + kwargs)]), - keyword=cst.Name("request") - ) - - return updated.with_changes( - args=[request_arg] + ctrl_kwargs - ) - - -def fix_files( - in_dir: pathlib.Path, - out_dir: pathlib.Path, - *, - transformer=edgecontainerCallTransformer(), -): - """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 edgecontainer 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-edgecontainer/v1/setup.py b/owl-bot-staging/google-cloud-edgecontainer/v1/setup.py deleted file mode 100644 index c28cdd5c6c72..000000000000 --- a/owl-bot-staging/google-cloud-edgecontainer/v1/setup.py +++ /dev/null @@ -1,98 +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-edgecontainer' - - -description = "Google Cloud Edgecontainer API client library" - -version = None - -with open(os.path.join(package_root, 'google/cloud/edgecontainer/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", -] -extras = { -} -url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-edgecontainer" - -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-edgecontainer/v1/testing/constraints-3.10.txt b/owl-bot-staging/google-cloud-edgecontainer/v1/testing/constraints-3.10.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-cloud-edgecontainer/v1/testing/constraints-3.10.txt +++ /dev/null @@ -1,6 +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 diff --git a/owl-bot-staging/google-cloud-edgecontainer/v1/testing/constraints-3.11.txt b/owl-bot-staging/google-cloud-edgecontainer/v1/testing/constraints-3.11.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-cloud-edgecontainer/v1/testing/constraints-3.11.txt +++ /dev/null @@ -1,6 +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 diff --git a/owl-bot-staging/google-cloud-edgecontainer/v1/testing/constraints-3.12.txt b/owl-bot-staging/google-cloud-edgecontainer/v1/testing/constraints-3.12.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-cloud-edgecontainer/v1/testing/constraints-3.12.txt +++ /dev/null @@ -1,6 +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 diff --git a/owl-bot-staging/google-cloud-edgecontainer/v1/testing/constraints-3.13.txt b/owl-bot-staging/google-cloud-edgecontainer/v1/testing/constraints-3.13.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-cloud-edgecontainer/v1/testing/constraints-3.13.txt +++ /dev/null @@ -1,6 +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 diff --git a/owl-bot-staging/google-cloud-edgecontainer/v1/testing/constraints-3.7.txt b/owl-bot-staging/google-cloud-edgecontainer/v1/testing/constraints-3.7.txt deleted file mode 100644 index fc812592b0ee..000000000000 --- a/owl-bot-staging/google-cloud-edgecontainer/v1/testing/constraints-3.7.txt +++ /dev/null @@ -1,10 +0,0 @@ -# This constraints file is used to check that lower bounds -# are correct in setup.py -# List all library dependencies and extras in this file. -# Pin the version to the lower bound. -# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0dev", -# Then this file should have google-cloud-foo==1.14.0 -google-api-core==1.34.1 -google-auth==2.14.1 -proto-plus==1.22.3 -protobuf==3.20.2 diff --git a/owl-bot-staging/google-cloud-edgecontainer/v1/testing/constraints-3.8.txt b/owl-bot-staging/google-cloud-edgecontainer/v1/testing/constraints-3.8.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-cloud-edgecontainer/v1/testing/constraints-3.8.txt +++ /dev/null @@ -1,6 +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 diff --git a/owl-bot-staging/google-cloud-edgecontainer/v1/testing/constraints-3.9.txt b/owl-bot-staging/google-cloud-edgecontainer/v1/testing/constraints-3.9.txt deleted file mode 100644 index ed7f9aed2559..000000000000 --- a/owl-bot-staging/google-cloud-edgecontainer/v1/testing/constraints-3.9.txt +++ /dev/null @@ -1,6 +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 diff --git a/owl-bot-staging/google-cloud-edgecontainer/v1/tests/__init__.py b/owl-bot-staging/google-cloud-edgecontainer/v1/tests/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-edgecontainer/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-edgecontainer/v1/tests/unit/__init__.py b/owl-bot-staging/google-cloud-edgecontainer/v1/tests/unit/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-edgecontainer/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-edgecontainer/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/google-cloud-edgecontainer/v1/tests/unit/gapic/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-edgecontainer/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-edgecontainer/v1/tests/unit/gapic/edgecontainer_v1/__init__.py b/owl-bot-staging/google-cloud-edgecontainer/v1/tests/unit/gapic/edgecontainer_v1/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-edgecontainer/v1/tests/unit/gapic/edgecontainer_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-edgecontainer/v1/tests/unit/gapic/edgecontainer_v1/test_edge_container.py b/owl-bot-staging/google-cloud-edgecontainer/v1/tests/unit/gapic/edgecontainer_v1/test_edge_container.py deleted file mode 100644 index 2c1e8bf9ff65..000000000000 --- a/owl-bot-staging/google-cloud-edgecontainer/v1/tests/unit/gapic/edgecontainer_v1/test_edge_container.py +++ /dev/null @@ -1,17403 +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_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.edgecontainer_v1.services.edge_container import EdgeContainerAsyncClient -from google.cloud.edgecontainer_v1.services.edge_container import EdgeContainerClient -from google.cloud.edgecontainer_v1.services.edge_container import pagers -from google.cloud.edgecontainer_v1.services.edge_container import transports -from google.cloud.edgecontainer_v1.types import resources -from google.cloud.edgecontainer_v1.types import service -from google.cloud.location import locations_pb2 -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 duration_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore -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 EdgeContainerClient._get_default_mtls_endpoint(None) is None - assert EdgeContainerClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert EdgeContainerClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert EdgeContainerClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert EdgeContainerClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert EdgeContainerClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - -def test__read_environment_variables(): - assert EdgeContainerClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert EdgeContainerClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert EdgeContainerClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - EdgeContainerClient._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 EdgeContainerClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert EdgeContainerClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert EdgeContainerClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - EdgeContainerClient._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 EdgeContainerClient._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 EdgeContainerClient._get_client_cert_source(None, False) is None - assert EdgeContainerClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert EdgeContainerClient._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 EdgeContainerClient._get_client_cert_source(None, True) is mock_default_cert_source - assert EdgeContainerClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(EdgeContainerClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EdgeContainerClient)) -@mock.patch.object(EdgeContainerAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EdgeContainerAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = EdgeContainerClient._DEFAULT_UNIVERSE - default_endpoint = EdgeContainerClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = EdgeContainerClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert EdgeContainerClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert EdgeContainerClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == EdgeContainerClient.DEFAULT_MTLS_ENDPOINT - assert EdgeContainerClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert EdgeContainerClient._get_api_endpoint(None, None, default_universe, "always") == EdgeContainerClient.DEFAULT_MTLS_ENDPOINT - assert EdgeContainerClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == EdgeContainerClient.DEFAULT_MTLS_ENDPOINT - assert EdgeContainerClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert EdgeContainerClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - EdgeContainerClient._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 EdgeContainerClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert EdgeContainerClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert EdgeContainerClient._get_universe_domain(None, None) == EdgeContainerClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - EdgeContainerClient._get_universe_domain("", None) - assert str(excinfo.value) == "Universe Domain cannot be an empty string." - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (EdgeContainerClient, transports.EdgeContainerGrpcTransport, "grpc"), - (EdgeContainerClient, transports.EdgeContainerRestTransport, "rest"), -]) -def test__validate_universe_domain(client_class, transport_class, transport_name): - client = client_class( - transport=transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - ) - assert client._validate_universe_domain() == True - - # Test the case when universe is already validated. - assert client._validate_universe_domain() == True - - if transport_name == "grpc": - # Test the case where credentials are provided by the - # `local_channel_credentials`. The default universes in both match. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - client = client_class(transport=transport_class(channel=channel)) - assert client._validate_universe_domain() == True - - # Test the case where credentials do not exist: e.g. a transport is provided - # with no credentials. Validation should still succeed because there is no - # mismatch with non-existent credentials. - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - transport=transport_class(channel=channel) - transport._credentials = None - client = client_class(transport=transport) - assert client._validate_universe_domain() == True - - # TODO: This is needed to cater for older versions of google-auth - # Make this test unconditional once the minimum supported version of - # google-auth becomes 2.23.0 or higher. - google_auth_major, google_auth_minor = [int(part) for part in google.auth.__version__.split(".")[0:2]] - if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): - credentials = ga_credentials.AnonymousCredentials() - credentials._universe_domain = "foo.com" - # Test the case when there is a universe mismatch from the credentials. - client = client_class( - transport=transport_class(credentials=credentials) - ) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test the case when there is a universe mismatch from the client. - # - # TODO: Make this test unconditional once the minimum supported version of - # google-api-core becomes 2.15.0 or higher. - api_core_major, api_core_minor = [int(part) for part in api_core_version.__version__.split(".")[0:2]] - if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): - client = client_class(client_options={"universe_domain": "bar.com"}, transport=transport_class(credentials=ga_credentials.AnonymousCredentials(),)) - with pytest.raises(ValueError) as excinfo: - client._validate_universe_domain() - assert str(excinfo.value) == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." - - # Test that ValueError is raised if universe_domain is provided via client options and credentials is None - with pytest.raises(ValueError): - client._compare_universes("foo.bar", None) - - -@pytest.mark.parametrize("client_class,transport_name", [ - (EdgeContainerClient, "grpc"), - (EdgeContainerAsyncClient, "grpc_asyncio"), - (EdgeContainerClient, "rest"), -]) -def test_edge_container_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 == ( - 'edgecontainer.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://edgecontainer.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.EdgeContainerGrpcTransport, "grpc"), - (transports.EdgeContainerGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.EdgeContainerRestTransport, "rest"), -]) -def test_edge_container_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", [ - (EdgeContainerClient, "grpc"), - (EdgeContainerAsyncClient, "grpc_asyncio"), - (EdgeContainerClient, "rest"), -]) -def test_edge_container_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 == ( - 'edgecontainer.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://edgecontainer.googleapis.com' - ) - - -def test_edge_container_client_get_transport_class(): - transport = EdgeContainerClient.get_transport_class() - available_transports = [ - transports.EdgeContainerGrpcTransport, - transports.EdgeContainerRestTransport, - ] - assert transport in available_transports - - transport = EdgeContainerClient.get_transport_class("grpc") - assert transport == transports.EdgeContainerGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (EdgeContainerClient, transports.EdgeContainerGrpcTransport, "grpc"), - (EdgeContainerAsyncClient, transports.EdgeContainerGrpcAsyncIOTransport, "grpc_asyncio"), - (EdgeContainerClient, transports.EdgeContainerRestTransport, "rest"), -]) -@mock.patch.object(EdgeContainerClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EdgeContainerClient)) -@mock.patch.object(EdgeContainerAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EdgeContainerAsyncClient)) -def test_edge_container_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(EdgeContainerClient, '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(EdgeContainerClient, '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", [ - (EdgeContainerClient, transports.EdgeContainerGrpcTransport, "grpc", "true"), - (EdgeContainerAsyncClient, transports.EdgeContainerGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (EdgeContainerClient, transports.EdgeContainerGrpcTransport, "grpc", "false"), - (EdgeContainerAsyncClient, transports.EdgeContainerGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (EdgeContainerClient, transports.EdgeContainerRestTransport, "rest", "true"), - (EdgeContainerClient, transports.EdgeContainerRestTransport, "rest", "false"), -]) -@mock.patch.object(EdgeContainerClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EdgeContainerClient)) -@mock.patch.object(EdgeContainerAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EdgeContainerAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_edge_container_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", [ - EdgeContainerClient, EdgeContainerAsyncClient -]) -@mock.patch.object(EdgeContainerClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EdgeContainerClient)) -@mock.patch.object(EdgeContainerAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EdgeContainerAsyncClient)) -def test_edge_container_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", [ - EdgeContainerClient, EdgeContainerAsyncClient -]) -@mock.patch.object(EdgeContainerClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EdgeContainerClient)) -@mock.patch.object(EdgeContainerAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EdgeContainerAsyncClient)) -def test_edge_container_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = EdgeContainerClient._DEFAULT_UNIVERSE - default_endpoint = EdgeContainerClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = EdgeContainerClient._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", [ - (EdgeContainerClient, transports.EdgeContainerGrpcTransport, "grpc"), - (EdgeContainerAsyncClient, transports.EdgeContainerGrpcAsyncIOTransport, "grpc_asyncio"), - (EdgeContainerClient, transports.EdgeContainerRestTransport, "rest"), -]) -def test_edge_container_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", [ - (EdgeContainerClient, transports.EdgeContainerGrpcTransport, "grpc", grpc_helpers), - (EdgeContainerAsyncClient, transports.EdgeContainerGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (EdgeContainerClient, transports.EdgeContainerRestTransport, "rest", None), -]) -def test_edge_container_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_edge_container_client_client_options_from_dict(): - with mock.patch('google.cloud.edgecontainer_v1.services.edge_container.transports.EdgeContainerGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = EdgeContainerClient( - 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", [ - (EdgeContainerClient, transports.EdgeContainerGrpcTransport, "grpc", grpc_helpers), - (EdgeContainerAsyncClient, transports.EdgeContainerGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_edge_container_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( - "edgecontainer.googleapis.com:443", - credentials=file_creds, - credentials_file=None, - quota_project_id=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - scopes=None, - default_host="edgecontainer.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - service.ListClustersRequest, - dict, -]) -def test_list_clusters(request_type, transport: str = 'grpc'): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_clusters), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service.ListClustersResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - ) - response = client.list_clusters(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = service.ListClustersRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListClustersPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -def test_list_clusters_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 = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = service.ListClustersRequest( - parent='parent_value', - page_token='page_token_value', - filter='filter_value', - order_by='order_by_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_clusters), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_clusters(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.ListClustersRequest( - parent='parent_value', - page_token='page_token_value', - filter='filter_value', - order_by='order_by_value', - ) - -def test_list_clusters_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = EdgeContainerClient( - 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_clusters in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_clusters] = mock_rpc - request = {} - client.list_clusters(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_clusters(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_list_clusters_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 = EdgeContainerAsyncClient( - 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_clusters 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_clusters] = mock_rpc - - request = {} - await client.list_clusters(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_clusters(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_list_clusters_async(transport: str = 'grpc_asyncio', request_type=service.ListClustersRequest): - client = EdgeContainerAsyncClient( - 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_clusters), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(service.ListClustersResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - )) - response = await client.list_clusters(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = service.ListClustersRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListClustersAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -@pytest.mark.asyncio -async def test_list_clusters_async_from_dict(): - await test_list_clusters_async(request_type=dict) - -def test_list_clusters_field_headers(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.ListClustersRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_clusters), - '__call__') as call: - call.return_value = service.ListClustersResponse() - client.list_clusters(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_list_clusters_field_headers_async(): - client = EdgeContainerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.ListClustersRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_clusters), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.ListClustersResponse()) - await client.list_clusters(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_list_clusters_flattened(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_clusters), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service.ListClustersResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_clusters( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - - -def test_list_clusters_flattened_error(): - client = EdgeContainerClient( - 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_clusters( - service.ListClustersRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_clusters_flattened_async(): - client = EdgeContainerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_clusters), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service.ListClustersResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.ListClustersResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_clusters( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_list_clusters_flattened_error_async(): - client = EdgeContainerAsyncClient( - 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_clusters( - service.ListClustersRequest(), - parent='parent_value', - ) - - -def test_list_clusters_pager(transport_name: str = "grpc"): - client = EdgeContainerClient( - 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_clusters), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - service.ListClustersResponse( - clusters=[ - resources.Cluster(), - resources.Cluster(), - resources.Cluster(), - ], - next_page_token='abc', - ), - service.ListClustersResponse( - clusters=[], - next_page_token='def', - ), - service.ListClustersResponse( - clusters=[ - resources.Cluster(), - ], - next_page_token='ghi', - ), - service.ListClustersResponse( - clusters=[ - resources.Cluster(), - resources.Cluster(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_clusters(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.Cluster) - for i in results) -def test_list_clusters_pages(transport_name: str = "grpc"): - client = EdgeContainerClient( - 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_clusters), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - service.ListClustersResponse( - clusters=[ - resources.Cluster(), - resources.Cluster(), - resources.Cluster(), - ], - next_page_token='abc', - ), - service.ListClustersResponse( - clusters=[], - next_page_token='def', - ), - service.ListClustersResponse( - clusters=[ - resources.Cluster(), - ], - next_page_token='ghi', - ), - service.ListClustersResponse( - clusters=[ - resources.Cluster(), - resources.Cluster(), - ], - ), - RuntimeError, - ) - pages = list(client.list_clusters(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_clusters_async_pager(): - client = EdgeContainerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_clusters), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - service.ListClustersResponse( - clusters=[ - resources.Cluster(), - resources.Cluster(), - resources.Cluster(), - ], - next_page_token='abc', - ), - service.ListClustersResponse( - clusters=[], - next_page_token='def', - ), - service.ListClustersResponse( - clusters=[ - resources.Cluster(), - ], - next_page_token='ghi', - ), - service.ListClustersResponse( - clusters=[ - resources.Cluster(), - resources.Cluster(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_clusters(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.Cluster) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_clusters_async_pages(): - client = EdgeContainerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_clusters), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - service.ListClustersResponse( - clusters=[ - resources.Cluster(), - resources.Cluster(), - resources.Cluster(), - ], - next_page_token='abc', - ), - service.ListClustersResponse( - clusters=[], - next_page_token='def', - ), - service.ListClustersResponse( - clusters=[ - resources.Cluster(), - ], - next_page_token='ghi', - ), - service.ListClustersResponse( - clusters=[ - resources.Cluster(), - resources.Cluster(), - ], - ), - 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_clusters(request={}) - ).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - service.GetClusterRequest, - dict, -]) -def test_get_cluster(request_type, transport: str = 'grpc'): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_cluster), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.Cluster( - name='name_value', - default_max_pods_per_node=2634, - endpoint='endpoint_value', - port=453, - cluster_ca_certificate='cluster_ca_certificate_value', - control_plane_version='control_plane_version_value', - node_version='node_version_value', - external_load_balancer_ipv4_address_pools=['external_load_balancer_ipv4_address_pools_value'], - status=resources.Cluster.Status.PROVISIONING, - target_version='target_version_value', - release_channel=resources.Cluster.ReleaseChannel.NONE, - external_load_balancer_ipv6_address_pools=['external_load_balancer_ipv6_address_pools_value'], - ) - response = client.get_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = service.GetClusterRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.Cluster) - assert response.name == 'name_value' - assert response.default_max_pods_per_node == 2634 - assert response.endpoint == 'endpoint_value' - assert response.port == 453 - assert response.cluster_ca_certificate == 'cluster_ca_certificate_value' - assert response.control_plane_version == 'control_plane_version_value' - assert response.node_version == 'node_version_value' - assert response.external_load_balancer_ipv4_address_pools == ['external_load_balancer_ipv4_address_pools_value'] - assert response.status == resources.Cluster.Status.PROVISIONING - assert response.target_version == 'target_version_value' - assert response.release_channel == resources.Cluster.ReleaseChannel.NONE - assert response.external_load_balancer_ipv6_address_pools == ['external_load_balancer_ipv6_address_pools_value'] - - -def test_get_cluster_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 = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = service.GetClusterRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_cluster), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_cluster(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.GetClusterRequest( - name='name_value', - ) - -def test_get_cluster_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = EdgeContainerClient( - 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_cluster in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_cluster] = mock_rpc - request = {} - client.get_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_cluster(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_get_cluster_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 = EdgeContainerAsyncClient( - 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_cluster 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_cluster] = mock_rpc - - request = {} - await client.get_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_cluster(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_get_cluster_async(transport: str = 'grpc_asyncio', request_type=service.GetClusterRequest): - client = EdgeContainerAsyncClient( - 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_cluster), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.Cluster( - name='name_value', - default_max_pods_per_node=2634, - endpoint='endpoint_value', - port=453, - cluster_ca_certificate='cluster_ca_certificate_value', - control_plane_version='control_plane_version_value', - node_version='node_version_value', - external_load_balancer_ipv4_address_pools=['external_load_balancer_ipv4_address_pools_value'], - status=resources.Cluster.Status.PROVISIONING, - target_version='target_version_value', - release_channel=resources.Cluster.ReleaseChannel.NONE, - external_load_balancer_ipv6_address_pools=['external_load_balancer_ipv6_address_pools_value'], - )) - response = await client.get_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = service.GetClusterRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.Cluster) - assert response.name == 'name_value' - assert response.default_max_pods_per_node == 2634 - assert response.endpoint == 'endpoint_value' - assert response.port == 453 - assert response.cluster_ca_certificate == 'cluster_ca_certificate_value' - assert response.control_plane_version == 'control_plane_version_value' - assert response.node_version == 'node_version_value' - assert response.external_load_balancer_ipv4_address_pools == ['external_load_balancer_ipv4_address_pools_value'] - assert response.status == resources.Cluster.Status.PROVISIONING - assert response.target_version == 'target_version_value' - assert response.release_channel == resources.Cluster.ReleaseChannel.NONE - assert response.external_load_balancer_ipv6_address_pools == ['external_load_balancer_ipv6_address_pools_value'] - - -@pytest.mark.asyncio -async def test_get_cluster_async_from_dict(): - await test_get_cluster_async(request_type=dict) - -def test_get_cluster_field_headers(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.GetClusterRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_cluster), - '__call__') as call: - call.return_value = resources.Cluster() - client.get_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_cluster_field_headers_async(): - client = EdgeContainerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.GetClusterRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_cluster), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Cluster()) - await client.get_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -def test_get_cluster_flattened(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_cluster), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.Cluster() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_cluster( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_get_cluster_flattened_error(): - client = EdgeContainerClient( - 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_cluster( - service.GetClusterRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_cluster_flattened_async(): - client = EdgeContainerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_cluster), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.Cluster() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Cluster()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_cluster( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_cluster_flattened_error_async(): - client = EdgeContainerAsyncClient( - 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_cluster( - service.GetClusterRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - service.CreateClusterRequest, - dict, -]) -def test_create_cluster(request_type, transport: str = 'grpc'): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_cluster), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.create_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = service.CreateClusterRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_create_cluster_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 = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = service.CreateClusterRequest( - parent='parent_value', - cluster_id='cluster_id_value', - request_id='request_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_cluster), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_cluster(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.CreateClusterRequest( - parent='parent_value', - cluster_id='cluster_id_value', - request_id='request_id_value', - ) - -def test_create_cluster_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = EdgeContainerClient( - 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_cluster in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.create_cluster] = mock_rpc - request = {} - client.create_cluster(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_cluster(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_create_cluster_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 = EdgeContainerAsyncClient( - 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_cluster 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_cluster] = mock_rpc - - request = {} - await client.create_cluster(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_cluster(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_create_cluster_async(transport: str = 'grpc_asyncio', request_type=service.CreateClusterRequest): - client = EdgeContainerAsyncClient( - 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_cluster), - '__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_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = service.CreateClusterRequest() - 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_cluster_async_from_dict(): - await test_create_cluster_async(request_type=dict) - -def test_create_cluster_field_headers(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.CreateClusterRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_cluster), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_create_cluster_field_headers_async(): - client = EdgeContainerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.CreateClusterRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_cluster), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.create_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_create_cluster_flattened(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_cluster), - '__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_cluster( - parent='parent_value', - cluster=resources.Cluster(name='name_value'), - cluster_id='cluster_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].cluster - mock_val = resources.Cluster(name='name_value') - assert arg == mock_val - arg = args[0].cluster_id - mock_val = 'cluster_id_value' - assert arg == mock_val - - -def test_create_cluster_flattened_error(): - client = EdgeContainerClient( - 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_cluster( - service.CreateClusterRequest(), - parent='parent_value', - cluster=resources.Cluster(name='name_value'), - cluster_id='cluster_id_value', - ) - -@pytest.mark.asyncio -async def test_create_cluster_flattened_async(): - client = EdgeContainerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_cluster), - '__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_cluster( - parent='parent_value', - cluster=resources.Cluster(name='name_value'), - cluster_id='cluster_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].cluster - mock_val = resources.Cluster(name='name_value') - assert arg == mock_val - arg = args[0].cluster_id - mock_val = 'cluster_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_cluster_flattened_error_async(): - client = EdgeContainerAsyncClient( - 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_cluster( - service.CreateClusterRequest(), - parent='parent_value', - cluster=resources.Cluster(name='name_value'), - cluster_id='cluster_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - service.UpdateClusterRequest, - dict, -]) -def test_update_cluster(request_type, transport: str = 'grpc'): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_cluster), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.update_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = service.UpdateClusterRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_update_cluster_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 = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = service.UpdateClusterRequest( - request_id='request_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_cluster), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_cluster(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.UpdateClusterRequest( - request_id='request_id_value', - ) - -def test_update_cluster_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.update_cluster in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_cluster] = mock_rpc - request = {} - client.update_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.update_cluster(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_update_cluster_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 = EdgeContainerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.update_cluster in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.update_cluster] = mock_rpc - - request = {} - await client.update_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.update_cluster(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_update_cluster_async(transport: str = 'grpc_asyncio', request_type=service.UpdateClusterRequest): - client = EdgeContainerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_cluster), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.update_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = service.UpdateClusterRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_update_cluster_async_from_dict(): - await test_update_cluster_async(request_type=dict) - -def test_update_cluster_field_headers(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.UpdateClusterRequest() - - request.cluster.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_cluster), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'cluster.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_cluster_field_headers_async(): - client = EdgeContainerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.UpdateClusterRequest() - - request.cluster.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_cluster), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.update_cluster(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', - 'cluster.name=name_value', - ) in kw['metadata'] - - -def test_update_cluster_flattened(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_cluster), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_cluster( - cluster=resources.Cluster(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].cluster - mock_val = resources.Cluster(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - - -def test_update_cluster_flattened_error(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.update_cluster( - service.UpdateClusterRequest(), - cluster=resources.Cluster(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_cluster_flattened_async(): - client = EdgeContainerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_cluster), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_cluster( - cluster=resources.Cluster(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].cluster - mock_val = resources.Cluster(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - -@pytest.mark.asyncio -async def test_update_cluster_flattened_error_async(): - client = EdgeContainerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_cluster( - service.UpdateClusterRequest(), - cluster=resources.Cluster(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - service.UpgradeClusterRequest, - dict, -]) -def test_upgrade_cluster(request_type, transport: str = 'grpc'): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.upgrade_cluster), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.upgrade_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = service.UpgradeClusterRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_upgrade_cluster_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 = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = service.UpgradeClusterRequest( - name='name_value', - target_version='target_version_value', - request_id='request_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.upgrade_cluster), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.upgrade_cluster(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.UpgradeClusterRequest( - name='name_value', - target_version='target_version_value', - request_id='request_id_value', - ) - -def test_upgrade_cluster_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = EdgeContainerClient( - 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.upgrade_cluster in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.upgrade_cluster] = mock_rpc - request = {} - client.upgrade_cluster(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.upgrade_cluster(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_upgrade_cluster_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 = EdgeContainerAsyncClient( - 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.upgrade_cluster 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.upgrade_cluster] = mock_rpc - - request = {} - await client.upgrade_cluster(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.upgrade_cluster(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_upgrade_cluster_async(transport: str = 'grpc_asyncio', request_type=service.UpgradeClusterRequest): - client = EdgeContainerAsyncClient( - 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.upgrade_cluster), - '__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.upgrade_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = service.UpgradeClusterRequest() - 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_upgrade_cluster_async_from_dict(): - await test_upgrade_cluster_async(request_type=dict) - -def test_upgrade_cluster_field_headers(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.UpgradeClusterRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.upgrade_cluster), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.upgrade_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_upgrade_cluster_field_headers_async(): - client = EdgeContainerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.UpgradeClusterRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.upgrade_cluster), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.upgrade_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -def test_upgrade_cluster_flattened(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.upgrade_cluster), - '__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.upgrade_cluster( - name='name_value', - target_version='target_version_value', - schedule=service.UpgradeClusterRequest.Schedule.IMMEDIATELY, - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - arg = args[0].target_version - mock_val = 'target_version_value' - assert arg == mock_val - arg = args[0].schedule - mock_val = service.UpgradeClusterRequest.Schedule.IMMEDIATELY - assert arg == mock_val - - -def test_upgrade_cluster_flattened_error(): - client = EdgeContainerClient( - 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.upgrade_cluster( - service.UpgradeClusterRequest(), - name='name_value', - target_version='target_version_value', - schedule=service.UpgradeClusterRequest.Schedule.IMMEDIATELY, - ) - -@pytest.mark.asyncio -async def test_upgrade_cluster_flattened_async(): - client = EdgeContainerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.upgrade_cluster), - '__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.upgrade_cluster( - name='name_value', - target_version='target_version_value', - schedule=service.UpgradeClusterRequest.Schedule.IMMEDIATELY, - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - arg = args[0].target_version - mock_val = 'target_version_value' - assert arg == mock_val - arg = args[0].schedule - mock_val = service.UpgradeClusterRequest.Schedule.IMMEDIATELY - assert arg == mock_val - -@pytest.mark.asyncio -async def test_upgrade_cluster_flattened_error_async(): - client = EdgeContainerAsyncClient( - 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.upgrade_cluster( - service.UpgradeClusterRequest(), - name='name_value', - target_version='target_version_value', - schedule=service.UpgradeClusterRequest.Schedule.IMMEDIATELY, - ) - - -@pytest.mark.parametrize("request_type", [ - service.DeleteClusterRequest, - dict, -]) -def test_delete_cluster(request_type, transport: str = 'grpc'): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_cluster), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.delete_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = service.DeleteClusterRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_delete_cluster_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 = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = service.DeleteClusterRequest( - name='name_value', - request_id='request_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_cluster), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_cluster(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.DeleteClusterRequest( - name='name_value', - request_id='request_id_value', - ) - -def test_delete_cluster_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = EdgeContainerClient( - 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_cluster in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.delete_cluster] = mock_rpc - request = {} - client.delete_cluster(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_cluster(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_delete_cluster_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 = EdgeContainerAsyncClient( - 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_cluster 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_cluster] = mock_rpc - - request = {} - await client.delete_cluster(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_cluster(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_delete_cluster_async(transport: str = 'grpc_asyncio', request_type=service.DeleteClusterRequest): - client = EdgeContainerAsyncClient( - 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_cluster), - '__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_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = service.DeleteClusterRequest() - 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_cluster_async_from_dict(): - await test_delete_cluster_async(request_type=dict) - -def test_delete_cluster_field_headers(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.DeleteClusterRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_cluster), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_delete_cluster_field_headers_async(): - client = EdgeContainerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.DeleteClusterRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_cluster), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.delete_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -def test_delete_cluster_flattened(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_cluster), - '__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_cluster( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_delete_cluster_flattened_error(): - client = EdgeContainerClient( - 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_cluster( - service.DeleteClusterRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_cluster_flattened_async(): - client = EdgeContainerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_cluster), - '__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_cluster( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_delete_cluster_flattened_error_async(): - client = EdgeContainerAsyncClient( - 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_cluster( - service.DeleteClusterRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - service.GenerateAccessTokenRequest, - dict, -]) -def test_generate_access_token(request_type, transport: str = 'grpc'): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_access_token), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service.GenerateAccessTokenResponse( - access_token='access_token_value', - ) - response = client.generate_access_token(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = service.GenerateAccessTokenRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, service.GenerateAccessTokenResponse) - assert response.access_token == 'access_token_value' - - -def test_generate_access_token_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 = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = service.GenerateAccessTokenRequest( - cluster='cluster_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_access_token), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.generate_access_token(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.GenerateAccessTokenRequest( - cluster='cluster_value', - ) - -def test_generate_access_token_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = EdgeContainerClient( - 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_access_token in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_access_token] = mock_rpc - request = {} - client.generate_access_token(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.generate_access_token(request) - - # Establish that 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_access_token_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 = EdgeContainerAsyncClient( - 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_access_token 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_access_token] = mock_rpc - - request = {} - await client.generate_access_token(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.generate_access_token(request) - - # Establish that 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_access_token_async(transport: str = 'grpc_asyncio', request_type=service.GenerateAccessTokenRequest): - client = EdgeContainerAsyncClient( - 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_access_token), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(service.GenerateAccessTokenResponse( - access_token='access_token_value', - )) - response = await client.generate_access_token(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = service.GenerateAccessTokenRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, service.GenerateAccessTokenResponse) - assert response.access_token == 'access_token_value' - - -@pytest.mark.asyncio -async def test_generate_access_token_async_from_dict(): - await test_generate_access_token_async(request_type=dict) - -def test_generate_access_token_field_headers(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.GenerateAccessTokenRequest() - - request.cluster = 'cluster_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_access_token), - '__call__') as call: - call.return_value = service.GenerateAccessTokenResponse() - client.generate_access_token(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'cluster=cluster_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_generate_access_token_field_headers_async(): - client = EdgeContainerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.GenerateAccessTokenRequest() - - request.cluster = 'cluster_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_access_token), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.GenerateAccessTokenResponse()) - await client.generate_access_token(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', - 'cluster=cluster_value', - ) in kw['metadata'] - - -def test_generate_access_token_flattened(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_access_token), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service.GenerateAccessTokenResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.generate_access_token( - cluster='cluster_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].cluster - mock_val = 'cluster_value' - assert arg == mock_val - - -def test_generate_access_token_flattened_error(): - client = EdgeContainerClient( - 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_access_token( - service.GenerateAccessTokenRequest(), - cluster='cluster_value', - ) - -@pytest.mark.asyncio -async def test_generate_access_token_flattened_async(): - client = EdgeContainerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_access_token), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service.GenerateAccessTokenResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.GenerateAccessTokenResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.generate_access_token( - cluster='cluster_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].cluster - mock_val = 'cluster_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_generate_access_token_flattened_error_async(): - client = EdgeContainerAsyncClient( - 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_access_token( - service.GenerateAccessTokenRequest(), - cluster='cluster_value', - ) - - -@pytest.mark.parametrize("request_type", [ - service.GenerateOfflineCredentialRequest, - dict, -]) -def test_generate_offline_credential(request_type, transport: str = 'grpc'): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_offline_credential), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service.GenerateOfflineCredentialResponse( - client_certificate='client_certificate_value', - client_key='client_key_value', - user_id='user_id_value', - ) - response = client.generate_offline_credential(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = service.GenerateOfflineCredentialRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, service.GenerateOfflineCredentialResponse) - assert response.client_certificate == 'client_certificate_value' - assert response.client_key == 'client_key_value' - assert response.user_id == 'user_id_value' - - -def test_generate_offline_credential_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 = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = service.GenerateOfflineCredentialRequest( - cluster='cluster_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_offline_credential), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.generate_offline_credential(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.GenerateOfflineCredentialRequest( - cluster='cluster_value', - ) - -def test_generate_offline_credential_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = EdgeContainerClient( - 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_offline_credential in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_offline_credential] = mock_rpc - request = {} - client.generate_offline_credential(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.generate_offline_credential(request) - - # Establish that 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_offline_credential_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 = EdgeContainerAsyncClient( - 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_offline_credential 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_offline_credential] = mock_rpc - - request = {} - await client.generate_offline_credential(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.generate_offline_credential(request) - - # Establish that 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_offline_credential_async(transport: str = 'grpc_asyncio', request_type=service.GenerateOfflineCredentialRequest): - client = EdgeContainerAsyncClient( - 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_offline_credential), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(service.GenerateOfflineCredentialResponse( - client_certificate='client_certificate_value', - client_key='client_key_value', - user_id='user_id_value', - )) - response = await client.generate_offline_credential(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = service.GenerateOfflineCredentialRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, service.GenerateOfflineCredentialResponse) - assert response.client_certificate == 'client_certificate_value' - assert response.client_key == 'client_key_value' - assert response.user_id == 'user_id_value' - - -@pytest.mark.asyncio -async def test_generate_offline_credential_async_from_dict(): - await test_generate_offline_credential_async(request_type=dict) - -def test_generate_offline_credential_field_headers(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.GenerateOfflineCredentialRequest() - - request.cluster = 'cluster_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_offline_credential), - '__call__') as call: - call.return_value = service.GenerateOfflineCredentialResponse() - client.generate_offline_credential(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'cluster=cluster_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_generate_offline_credential_field_headers_async(): - client = EdgeContainerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.GenerateOfflineCredentialRequest() - - request.cluster = 'cluster_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_offline_credential), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.GenerateOfflineCredentialResponse()) - await client.generate_offline_credential(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', - 'cluster=cluster_value', - ) in kw['metadata'] - - -def test_generate_offline_credential_flattened(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_offline_credential), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service.GenerateOfflineCredentialResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.generate_offline_credential( - cluster='cluster_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].cluster - mock_val = 'cluster_value' - assert arg == mock_val - - -def test_generate_offline_credential_flattened_error(): - client = EdgeContainerClient( - 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_offline_credential( - service.GenerateOfflineCredentialRequest(), - cluster='cluster_value', - ) - -@pytest.mark.asyncio -async def test_generate_offline_credential_flattened_async(): - client = EdgeContainerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_offline_credential), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service.GenerateOfflineCredentialResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.GenerateOfflineCredentialResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.generate_offline_credential( - cluster='cluster_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].cluster - mock_val = 'cluster_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_generate_offline_credential_flattened_error_async(): - client = EdgeContainerAsyncClient( - 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_offline_credential( - service.GenerateOfflineCredentialRequest(), - cluster='cluster_value', - ) - - -@pytest.mark.parametrize("request_type", [ - service.ListNodePoolsRequest, - dict, -]) -def test_list_node_pools(request_type, transport: str = 'grpc'): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_node_pools), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service.ListNodePoolsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - ) - response = client.list_node_pools(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = service.ListNodePoolsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListNodePoolsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -def test_list_node_pools_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 = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = service.ListNodePoolsRequest( - parent='parent_value', - page_token='page_token_value', - filter='filter_value', - order_by='order_by_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_node_pools), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_node_pools(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.ListNodePoolsRequest( - parent='parent_value', - page_token='page_token_value', - filter='filter_value', - order_by='order_by_value', - ) - -def test_list_node_pools_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = EdgeContainerClient( - 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_node_pools in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_node_pools] = mock_rpc - request = {} - client.list_node_pools(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_node_pools(request) - - # Establish that 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_node_pools_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 = EdgeContainerAsyncClient( - 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_node_pools 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_node_pools] = mock_rpc - - request = {} - await client.list_node_pools(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_node_pools(request) - - # Establish that 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_node_pools_async(transport: str = 'grpc_asyncio', request_type=service.ListNodePoolsRequest): - client = EdgeContainerAsyncClient( - 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_node_pools), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(service.ListNodePoolsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - )) - response = await client.list_node_pools(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = service.ListNodePoolsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListNodePoolsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -@pytest.mark.asyncio -async def test_list_node_pools_async_from_dict(): - await test_list_node_pools_async(request_type=dict) - -def test_list_node_pools_field_headers(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.ListNodePoolsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_node_pools), - '__call__') as call: - call.return_value = service.ListNodePoolsResponse() - client.list_node_pools(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_list_node_pools_field_headers_async(): - client = EdgeContainerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.ListNodePoolsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_node_pools), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.ListNodePoolsResponse()) - await client.list_node_pools(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_list_node_pools_flattened(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_node_pools), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service.ListNodePoolsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_node_pools( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - - -def test_list_node_pools_flattened_error(): - client = EdgeContainerClient( - 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_node_pools( - service.ListNodePoolsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_node_pools_flattened_async(): - client = EdgeContainerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_node_pools), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service.ListNodePoolsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.ListNodePoolsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_node_pools( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_list_node_pools_flattened_error_async(): - client = EdgeContainerAsyncClient( - 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_node_pools( - service.ListNodePoolsRequest(), - parent='parent_value', - ) - - -def test_list_node_pools_pager(transport_name: str = "grpc"): - client = EdgeContainerClient( - 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_node_pools), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - service.ListNodePoolsResponse( - node_pools=[ - resources.NodePool(), - resources.NodePool(), - resources.NodePool(), - ], - next_page_token='abc', - ), - service.ListNodePoolsResponse( - node_pools=[], - next_page_token='def', - ), - service.ListNodePoolsResponse( - node_pools=[ - resources.NodePool(), - ], - next_page_token='ghi', - ), - service.ListNodePoolsResponse( - node_pools=[ - resources.NodePool(), - resources.NodePool(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_node_pools(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.NodePool) - for i in results) -def test_list_node_pools_pages(transport_name: str = "grpc"): - client = EdgeContainerClient( - 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_node_pools), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - service.ListNodePoolsResponse( - node_pools=[ - resources.NodePool(), - resources.NodePool(), - resources.NodePool(), - ], - next_page_token='abc', - ), - service.ListNodePoolsResponse( - node_pools=[], - next_page_token='def', - ), - service.ListNodePoolsResponse( - node_pools=[ - resources.NodePool(), - ], - next_page_token='ghi', - ), - service.ListNodePoolsResponse( - node_pools=[ - resources.NodePool(), - resources.NodePool(), - ], - ), - RuntimeError, - ) - pages = list(client.list_node_pools(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_node_pools_async_pager(): - client = EdgeContainerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_node_pools), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - service.ListNodePoolsResponse( - node_pools=[ - resources.NodePool(), - resources.NodePool(), - resources.NodePool(), - ], - next_page_token='abc', - ), - service.ListNodePoolsResponse( - node_pools=[], - next_page_token='def', - ), - service.ListNodePoolsResponse( - node_pools=[ - resources.NodePool(), - ], - next_page_token='ghi', - ), - service.ListNodePoolsResponse( - node_pools=[ - resources.NodePool(), - resources.NodePool(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_node_pools(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.NodePool) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_node_pools_async_pages(): - client = EdgeContainerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_node_pools), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - service.ListNodePoolsResponse( - node_pools=[ - resources.NodePool(), - resources.NodePool(), - resources.NodePool(), - ], - next_page_token='abc', - ), - service.ListNodePoolsResponse( - node_pools=[], - next_page_token='def', - ), - service.ListNodePoolsResponse( - node_pools=[ - resources.NodePool(), - ], - next_page_token='ghi', - ), - service.ListNodePoolsResponse( - node_pools=[ - resources.NodePool(), - resources.NodePool(), - ], - ), - 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_node_pools(request={}) - ).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - service.GetNodePoolRequest, - dict, -]) -def test_get_node_pool(request_type, transport: str = 'grpc'): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_node_pool), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.NodePool( - name='name_value', - node_location='node_location_value', - node_count=1070, - machine_filter='machine_filter_value', - node_version='node_version_value', - ) - response = client.get_node_pool(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = service.GetNodePoolRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.NodePool) - assert response.name == 'name_value' - assert response.node_location == 'node_location_value' - assert response.node_count == 1070 - assert response.machine_filter == 'machine_filter_value' - assert response.node_version == 'node_version_value' - - -def test_get_node_pool_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 = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = service.GetNodePoolRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_node_pool), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_node_pool(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.GetNodePoolRequest( - name='name_value', - ) - -def test_get_node_pool_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = EdgeContainerClient( - 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_node_pool in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_node_pool] = mock_rpc - request = {} - client.get_node_pool(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_node_pool(request) - - # Establish that 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_node_pool_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 = EdgeContainerAsyncClient( - 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_node_pool 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_node_pool] = mock_rpc - - request = {} - await client.get_node_pool(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_node_pool(request) - - # Establish that 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_node_pool_async(transport: str = 'grpc_asyncio', request_type=service.GetNodePoolRequest): - client = EdgeContainerAsyncClient( - 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_node_pool), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.NodePool( - name='name_value', - node_location='node_location_value', - node_count=1070, - machine_filter='machine_filter_value', - node_version='node_version_value', - )) - response = await client.get_node_pool(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = service.GetNodePoolRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.NodePool) - assert response.name == 'name_value' - assert response.node_location == 'node_location_value' - assert response.node_count == 1070 - assert response.machine_filter == 'machine_filter_value' - assert response.node_version == 'node_version_value' - - -@pytest.mark.asyncio -async def test_get_node_pool_async_from_dict(): - await test_get_node_pool_async(request_type=dict) - -def test_get_node_pool_field_headers(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.GetNodePoolRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_node_pool), - '__call__') as call: - call.return_value = resources.NodePool() - client.get_node_pool(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_node_pool_field_headers_async(): - client = EdgeContainerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.GetNodePoolRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_node_pool), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.NodePool()) - await client.get_node_pool(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -def test_get_node_pool_flattened(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_node_pool), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.NodePool() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_node_pool( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_get_node_pool_flattened_error(): - client = EdgeContainerClient( - 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_node_pool( - service.GetNodePoolRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_node_pool_flattened_async(): - client = EdgeContainerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_node_pool), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.NodePool() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.NodePool()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_node_pool( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_node_pool_flattened_error_async(): - client = EdgeContainerAsyncClient( - 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_node_pool( - service.GetNodePoolRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - service.CreateNodePoolRequest, - dict, -]) -def test_create_node_pool(request_type, transport: str = 'grpc'): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_node_pool), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.create_node_pool(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = service.CreateNodePoolRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_create_node_pool_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 = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = service.CreateNodePoolRequest( - parent='parent_value', - node_pool_id='node_pool_id_value', - request_id='request_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_node_pool), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_node_pool(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.CreateNodePoolRequest( - parent='parent_value', - node_pool_id='node_pool_id_value', - request_id='request_id_value', - ) - -def test_create_node_pool_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = EdgeContainerClient( - 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_node_pool in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_node_pool] = mock_rpc - request = {} - client.create_node_pool(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_node_pool(request) - - # Establish that 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_node_pool_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 = EdgeContainerAsyncClient( - 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_node_pool 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_node_pool] = mock_rpc - - request = {} - await client.create_node_pool(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_node_pool(request) - - # Establish that 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_node_pool_async(transport: str = 'grpc_asyncio', request_type=service.CreateNodePoolRequest): - client = EdgeContainerAsyncClient( - 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_node_pool), - '__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_node_pool(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = service.CreateNodePoolRequest() - 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_node_pool_async_from_dict(): - await test_create_node_pool_async(request_type=dict) - -def test_create_node_pool_field_headers(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.CreateNodePoolRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_node_pool), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_node_pool(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_create_node_pool_field_headers_async(): - client = EdgeContainerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.CreateNodePoolRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_node_pool), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.create_node_pool(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_create_node_pool_flattened(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_node_pool), - '__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_node_pool( - parent='parent_value', - node_pool=resources.NodePool(name='name_value'), - node_pool_id='node_pool_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].node_pool - mock_val = resources.NodePool(name='name_value') - assert arg == mock_val - arg = args[0].node_pool_id - mock_val = 'node_pool_id_value' - assert arg == mock_val - - -def test_create_node_pool_flattened_error(): - client = EdgeContainerClient( - 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_node_pool( - service.CreateNodePoolRequest(), - parent='parent_value', - node_pool=resources.NodePool(name='name_value'), - node_pool_id='node_pool_id_value', - ) - -@pytest.mark.asyncio -async def test_create_node_pool_flattened_async(): - client = EdgeContainerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_node_pool), - '__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_node_pool( - parent='parent_value', - node_pool=resources.NodePool(name='name_value'), - node_pool_id='node_pool_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].node_pool - mock_val = resources.NodePool(name='name_value') - assert arg == mock_val - arg = args[0].node_pool_id - mock_val = 'node_pool_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_node_pool_flattened_error_async(): - client = EdgeContainerAsyncClient( - 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_node_pool( - service.CreateNodePoolRequest(), - parent='parent_value', - node_pool=resources.NodePool(name='name_value'), - node_pool_id='node_pool_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - service.UpdateNodePoolRequest, - dict, -]) -def test_update_node_pool(request_type, transport: str = 'grpc'): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_node_pool), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.update_node_pool(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = service.UpdateNodePoolRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_update_node_pool_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 = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = service.UpdateNodePoolRequest( - request_id='request_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_node_pool), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_node_pool(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.UpdateNodePoolRequest( - request_id='request_id_value', - ) - -def test_update_node_pool_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.update_node_pool in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_node_pool] = mock_rpc - request = {} - client.update_node_pool(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.update_node_pool(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_update_node_pool_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 = EdgeContainerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.update_node_pool in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.update_node_pool] = mock_rpc - - request = {} - await client.update_node_pool(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.update_node_pool(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_update_node_pool_async(transport: str = 'grpc_asyncio', request_type=service.UpdateNodePoolRequest): - client = EdgeContainerAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_node_pool), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.update_node_pool(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = service.UpdateNodePoolRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_update_node_pool_async_from_dict(): - await test_update_node_pool_async(request_type=dict) - -def test_update_node_pool_field_headers(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.UpdateNodePoolRequest() - - request.node_pool.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_node_pool), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_node_pool(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'node_pool.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_node_pool_field_headers_async(): - client = EdgeContainerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.UpdateNodePoolRequest() - - request.node_pool.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_node_pool), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.update_node_pool(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', - 'node_pool.name=name_value', - ) in kw['metadata'] - - -def test_update_node_pool_flattened(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_node_pool), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_node_pool( - node_pool=resources.NodePool(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].node_pool - mock_val = resources.NodePool(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - - -def test_update_node_pool_flattened_error(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.update_node_pool( - service.UpdateNodePoolRequest(), - node_pool=resources.NodePool(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_node_pool_flattened_async(): - client = EdgeContainerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_node_pool), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_node_pool( - node_pool=resources.NodePool(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].node_pool - mock_val = resources.NodePool(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - -@pytest.mark.asyncio -async def test_update_node_pool_flattened_error_async(): - client = EdgeContainerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_node_pool( - service.UpdateNodePoolRequest(), - node_pool=resources.NodePool(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - service.DeleteNodePoolRequest, - dict, -]) -def test_delete_node_pool(request_type, transport: str = 'grpc'): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_node_pool), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.delete_node_pool(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = service.DeleteNodePoolRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_delete_node_pool_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 = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = service.DeleteNodePoolRequest( - name='name_value', - request_id='request_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_node_pool), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_node_pool(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.DeleteNodePoolRequest( - name='name_value', - request_id='request_id_value', - ) - -def test_delete_node_pool_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = EdgeContainerClient( - 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_node_pool in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_node_pool] = mock_rpc - request = {} - client.delete_node_pool(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_node_pool(request) - - # Establish that 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_node_pool_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 = EdgeContainerAsyncClient( - 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_node_pool 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_node_pool] = mock_rpc - - request = {} - await client.delete_node_pool(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_node_pool(request) - - # Establish that 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_node_pool_async(transport: str = 'grpc_asyncio', request_type=service.DeleteNodePoolRequest): - client = EdgeContainerAsyncClient( - 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_node_pool), - '__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_node_pool(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = service.DeleteNodePoolRequest() - 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_node_pool_async_from_dict(): - await test_delete_node_pool_async(request_type=dict) - -def test_delete_node_pool_field_headers(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.DeleteNodePoolRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_node_pool), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_node_pool(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_delete_node_pool_field_headers_async(): - client = EdgeContainerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.DeleteNodePoolRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_node_pool), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.delete_node_pool(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -def test_delete_node_pool_flattened(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_node_pool), - '__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_node_pool( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_delete_node_pool_flattened_error(): - client = EdgeContainerClient( - 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_node_pool( - service.DeleteNodePoolRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_node_pool_flattened_async(): - client = EdgeContainerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_node_pool), - '__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_node_pool( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_delete_node_pool_flattened_error_async(): - client = EdgeContainerAsyncClient( - 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_node_pool( - service.DeleteNodePoolRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - service.ListMachinesRequest, - dict, -]) -def test_list_machines(request_type, transport: str = 'grpc'): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_machines), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service.ListMachinesResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - ) - response = client.list_machines(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = service.ListMachinesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListMachinesPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -def test_list_machines_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 = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = service.ListMachinesRequest( - parent='parent_value', - page_token='page_token_value', - filter='filter_value', - order_by='order_by_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_machines), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_machines(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.ListMachinesRequest( - parent='parent_value', - page_token='page_token_value', - filter='filter_value', - order_by='order_by_value', - ) - -def test_list_machines_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = EdgeContainerClient( - 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_machines in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_machines] = mock_rpc - request = {} - client.list_machines(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_machines(request) - - # Establish that 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_machines_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 = EdgeContainerAsyncClient( - 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_machines 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_machines] = mock_rpc - - request = {} - await client.list_machines(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_machines(request) - - # Establish that 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_machines_async(transport: str = 'grpc_asyncio', request_type=service.ListMachinesRequest): - client = EdgeContainerAsyncClient( - 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_machines), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(service.ListMachinesResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - )) - response = await client.list_machines(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = service.ListMachinesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListMachinesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -@pytest.mark.asyncio -async def test_list_machines_async_from_dict(): - await test_list_machines_async(request_type=dict) - -def test_list_machines_field_headers(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.ListMachinesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_machines), - '__call__') as call: - call.return_value = service.ListMachinesResponse() - client.list_machines(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_list_machines_field_headers_async(): - client = EdgeContainerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.ListMachinesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_machines), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.ListMachinesResponse()) - await client.list_machines(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_list_machines_flattened(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_machines), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service.ListMachinesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_machines( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - - -def test_list_machines_flattened_error(): - client = EdgeContainerClient( - 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_machines( - service.ListMachinesRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_machines_flattened_async(): - client = EdgeContainerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_machines), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service.ListMachinesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.ListMachinesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_machines( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_list_machines_flattened_error_async(): - client = EdgeContainerAsyncClient( - 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_machines( - service.ListMachinesRequest(), - parent='parent_value', - ) - - -def test_list_machines_pager(transport_name: str = "grpc"): - client = EdgeContainerClient( - 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_machines), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - service.ListMachinesResponse( - machines=[ - resources.Machine(), - resources.Machine(), - resources.Machine(), - ], - next_page_token='abc', - ), - service.ListMachinesResponse( - machines=[], - next_page_token='def', - ), - service.ListMachinesResponse( - machines=[ - resources.Machine(), - ], - next_page_token='ghi', - ), - service.ListMachinesResponse( - machines=[ - resources.Machine(), - resources.Machine(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_machines(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.Machine) - for i in results) -def test_list_machines_pages(transport_name: str = "grpc"): - client = EdgeContainerClient( - 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_machines), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - service.ListMachinesResponse( - machines=[ - resources.Machine(), - resources.Machine(), - resources.Machine(), - ], - next_page_token='abc', - ), - service.ListMachinesResponse( - machines=[], - next_page_token='def', - ), - service.ListMachinesResponse( - machines=[ - resources.Machine(), - ], - next_page_token='ghi', - ), - service.ListMachinesResponse( - machines=[ - resources.Machine(), - resources.Machine(), - ], - ), - RuntimeError, - ) - pages = list(client.list_machines(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_machines_async_pager(): - client = EdgeContainerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_machines), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - service.ListMachinesResponse( - machines=[ - resources.Machine(), - resources.Machine(), - resources.Machine(), - ], - next_page_token='abc', - ), - service.ListMachinesResponse( - machines=[], - next_page_token='def', - ), - service.ListMachinesResponse( - machines=[ - resources.Machine(), - ], - next_page_token='ghi', - ), - service.ListMachinesResponse( - machines=[ - resources.Machine(), - resources.Machine(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_machines(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.Machine) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_machines_async_pages(): - client = EdgeContainerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_machines), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - service.ListMachinesResponse( - machines=[ - resources.Machine(), - resources.Machine(), - resources.Machine(), - ], - next_page_token='abc', - ), - service.ListMachinesResponse( - machines=[], - next_page_token='def', - ), - service.ListMachinesResponse( - machines=[ - resources.Machine(), - ], - next_page_token='ghi', - ), - service.ListMachinesResponse( - machines=[ - resources.Machine(), - resources.Machine(), - ], - ), - 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_machines(request={}) - ).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - service.GetMachineRequest, - dict, -]) -def test_get_machine(request_type, transport: str = 'grpc'): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_machine), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.Machine( - name='name_value', - hosted_node='hosted_node_value', - zone='zone_value', - version='version_value', - disabled=True, - ) - response = client.get_machine(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = service.GetMachineRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.Machine) - assert response.name == 'name_value' - assert response.hosted_node == 'hosted_node_value' - assert response.zone == 'zone_value' - assert response.version == 'version_value' - assert response.disabled is True - - -def test_get_machine_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 = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = service.GetMachineRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_machine), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_machine(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.GetMachineRequest( - name='name_value', - ) - -def test_get_machine_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = EdgeContainerClient( - 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_machine in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_machine] = mock_rpc - request = {} - client.get_machine(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_machine(request) - - # Establish that 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_machine_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 = EdgeContainerAsyncClient( - 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_machine 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_machine] = mock_rpc - - request = {} - await client.get_machine(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_machine(request) - - # Establish that 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_machine_async(transport: str = 'grpc_asyncio', request_type=service.GetMachineRequest): - client = EdgeContainerAsyncClient( - 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_machine), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.Machine( - name='name_value', - hosted_node='hosted_node_value', - zone='zone_value', - version='version_value', - disabled=True, - )) - response = await client.get_machine(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = service.GetMachineRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.Machine) - assert response.name == 'name_value' - assert response.hosted_node == 'hosted_node_value' - assert response.zone == 'zone_value' - assert response.version == 'version_value' - assert response.disabled is True - - -@pytest.mark.asyncio -async def test_get_machine_async_from_dict(): - await test_get_machine_async(request_type=dict) - -def test_get_machine_field_headers(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.GetMachineRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_machine), - '__call__') as call: - call.return_value = resources.Machine() - client.get_machine(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_machine_field_headers_async(): - client = EdgeContainerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.GetMachineRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_machine), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Machine()) - await client.get_machine(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -def test_get_machine_flattened(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_machine), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.Machine() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_machine( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_get_machine_flattened_error(): - client = EdgeContainerClient( - 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_machine( - service.GetMachineRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_machine_flattened_async(): - client = EdgeContainerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_machine), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.Machine() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Machine()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_machine( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_machine_flattened_error_async(): - client = EdgeContainerAsyncClient( - 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_machine( - service.GetMachineRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - service.ListVpnConnectionsRequest, - dict, -]) -def test_list_vpn_connections(request_type, transport: str = 'grpc'): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_vpn_connections), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service.ListVpnConnectionsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - ) - response = client.list_vpn_connections(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = service.ListVpnConnectionsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListVpnConnectionsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -def test_list_vpn_connections_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 = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = service.ListVpnConnectionsRequest( - parent='parent_value', - page_token='page_token_value', - filter='filter_value', - order_by='order_by_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_vpn_connections), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_vpn_connections(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.ListVpnConnectionsRequest( - parent='parent_value', - page_token='page_token_value', - filter='filter_value', - order_by='order_by_value', - ) - -def test_list_vpn_connections_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = EdgeContainerClient( - 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_vpn_connections in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_vpn_connections] = mock_rpc - request = {} - client.list_vpn_connections(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_vpn_connections(request) - - # Establish that 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_vpn_connections_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 = EdgeContainerAsyncClient( - 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_vpn_connections 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_vpn_connections] = mock_rpc - - request = {} - await client.list_vpn_connections(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_vpn_connections(request) - - # Establish that 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_vpn_connections_async(transport: str = 'grpc_asyncio', request_type=service.ListVpnConnectionsRequest): - client = EdgeContainerAsyncClient( - 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_vpn_connections), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(service.ListVpnConnectionsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - )) - response = await client.list_vpn_connections(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = service.ListVpnConnectionsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListVpnConnectionsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -@pytest.mark.asyncio -async def test_list_vpn_connections_async_from_dict(): - await test_list_vpn_connections_async(request_type=dict) - -def test_list_vpn_connections_field_headers(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.ListVpnConnectionsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_vpn_connections), - '__call__') as call: - call.return_value = service.ListVpnConnectionsResponse() - client.list_vpn_connections(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_list_vpn_connections_field_headers_async(): - client = EdgeContainerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.ListVpnConnectionsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_vpn_connections), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.ListVpnConnectionsResponse()) - await client.list_vpn_connections(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_list_vpn_connections_flattened(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_vpn_connections), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service.ListVpnConnectionsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_vpn_connections( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - - -def test_list_vpn_connections_flattened_error(): - client = EdgeContainerClient( - 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_vpn_connections( - service.ListVpnConnectionsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_vpn_connections_flattened_async(): - client = EdgeContainerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_vpn_connections), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service.ListVpnConnectionsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.ListVpnConnectionsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_vpn_connections( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_list_vpn_connections_flattened_error_async(): - client = EdgeContainerAsyncClient( - 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_vpn_connections( - service.ListVpnConnectionsRequest(), - parent='parent_value', - ) - - -def test_list_vpn_connections_pager(transport_name: str = "grpc"): - client = EdgeContainerClient( - 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_vpn_connections), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - service.ListVpnConnectionsResponse( - vpn_connections=[ - resources.VpnConnection(), - resources.VpnConnection(), - resources.VpnConnection(), - ], - next_page_token='abc', - ), - service.ListVpnConnectionsResponse( - vpn_connections=[], - next_page_token='def', - ), - service.ListVpnConnectionsResponse( - vpn_connections=[ - resources.VpnConnection(), - ], - next_page_token='ghi', - ), - service.ListVpnConnectionsResponse( - vpn_connections=[ - resources.VpnConnection(), - resources.VpnConnection(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_vpn_connections(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.VpnConnection) - for i in results) -def test_list_vpn_connections_pages(transport_name: str = "grpc"): - client = EdgeContainerClient( - 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_vpn_connections), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - service.ListVpnConnectionsResponse( - vpn_connections=[ - resources.VpnConnection(), - resources.VpnConnection(), - resources.VpnConnection(), - ], - next_page_token='abc', - ), - service.ListVpnConnectionsResponse( - vpn_connections=[], - next_page_token='def', - ), - service.ListVpnConnectionsResponse( - vpn_connections=[ - resources.VpnConnection(), - ], - next_page_token='ghi', - ), - service.ListVpnConnectionsResponse( - vpn_connections=[ - resources.VpnConnection(), - resources.VpnConnection(), - ], - ), - RuntimeError, - ) - pages = list(client.list_vpn_connections(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_vpn_connections_async_pager(): - client = EdgeContainerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_vpn_connections), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - service.ListVpnConnectionsResponse( - vpn_connections=[ - resources.VpnConnection(), - resources.VpnConnection(), - resources.VpnConnection(), - ], - next_page_token='abc', - ), - service.ListVpnConnectionsResponse( - vpn_connections=[], - next_page_token='def', - ), - service.ListVpnConnectionsResponse( - vpn_connections=[ - resources.VpnConnection(), - ], - next_page_token='ghi', - ), - service.ListVpnConnectionsResponse( - vpn_connections=[ - resources.VpnConnection(), - resources.VpnConnection(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_vpn_connections(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.VpnConnection) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_vpn_connections_async_pages(): - client = EdgeContainerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_vpn_connections), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - service.ListVpnConnectionsResponse( - vpn_connections=[ - resources.VpnConnection(), - resources.VpnConnection(), - resources.VpnConnection(), - ], - next_page_token='abc', - ), - service.ListVpnConnectionsResponse( - vpn_connections=[], - next_page_token='def', - ), - service.ListVpnConnectionsResponse( - vpn_connections=[ - resources.VpnConnection(), - ], - next_page_token='ghi', - ), - service.ListVpnConnectionsResponse( - vpn_connections=[ - resources.VpnConnection(), - resources.VpnConnection(), - ], - ), - 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_vpn_connections(request={}) - ).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - service.GetVpnConnectionRequest, - dict, -]) -def test_get_vpn_connection(request_type, transport: str = 'grpc'): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_vpn_connection), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.VpnConnection( - name='name_value', - nat_gateway_ip='nat_gateway_ip_value', - bgp_routing_mode=resources.VpnConnection.BgpRoutingMode.REGIONAL, - cluster='cluster_value', - vpc='vpc_value', - enable_high_availability=True, - router='router_value', - ) - response = client.get_vpn_connection(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = service.GetVpnConnectionRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.VpnConnection) - assert response.name == 'name_value' - assert response.nat_gateway_ip == 'nat_gateway_ip_value' - assert response.bgp_routing_mode == resources.VpnConnection.BgpRoutingMode.REGIONAL - assert response.cluster == 'cluster_value' - assert response.vpc == 'vpc_value' - assert response.enable_high_availability is True - assert response.router == 'router_value' - - -def test_get_vpn_connection_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 = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = service.GetVpnConnectionRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_vpn_connection), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_vpn_connection(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.GetVpnConnectionRequest( - name='name_value', - ) - -def test_get_vpn_connection_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = EdgeContainerClient( - 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_vpn_connection in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_vpn_connection] = mock_rpc - request = {} - client.get_vpn_connection(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_vpn_connection(request) - - # Establish that 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_vpn_connection_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 = EdgeContainerAsyncClient( - 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_vpn_connection 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_vpn_connection] = mock_rpc - - request = {} - await client.get_vpn_connection(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_vpn_connection(request) - - # Establish that 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_vpn_connection_async(transport: str = 'grpc_asyncio', request_type=service.GetVpnConnectionRequest): - client = EdgeContainerAsyncClient( - 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_vpn_connection), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.VpnConnection( - name='name_value', - nat_gateway_ip='nat_gateway_ip_value', - bgp_routing_mode=resources.VpnConnection.BgpRoutingMode.REGIONAL, - cluster='cluster_value', - vpc='vpc_value', - enable_high_availability=True, - router='router_value', - )) - response = await client.get_vpn_connection(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = service.GetVpnConnectionRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.VpnConnection) - assert response.name == 'name_value' - assert response.nat_gateway_ip == 'nat_gateway_ip_value' - assert response.bgp_routing_mode == resources.VpnConnection.BgpRoutingMode.REGIONAL - assert response.cluster == 'cluster_value' - assert response.vpc == 'vpc_value' - assert response.enable_high_availability is True - assert response.router == 'router_value' - - -@pytest.mark.asyncio -async def test_get_vpn_connection_async_from_dict(): - await test_get_vpn_connection_async(request_type=dict) - -def test_get_vpn_connection_field_headers(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.GetVpnConnectionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_vpn_connection), - '__call__') as call: - call.return_value = resources.VpnConnection() - client.get_vpn_connection(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_vpn_connection_field_headers_async(): - client = EdgeContainerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.GetVpnConnectionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_vpn_connection), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.VpnConnection()) - await client.get_vpn_connection(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -def test_get_vpn_connection_flattened(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_vpn_connection), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.VpnConnection() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_vpn_connection( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_get_vpn_connection_flattened_error(): - client = EdgeContainerClient( - 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_vpn_connection( - service.GetVpnConnectionRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_vpn_connection_flattened_async(): - client = EdgeContainerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_vpn_connection), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.VpnConnection() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.VpnConnection()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_vpn_connection( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_vpn_connection_flattened_error_async(): - client = EdgeContainerAsyncClient( - 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_vpn_connection( - service.GetVpnConnectionRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - service.CreateVpnConnectionRequest, - dict, -]) -def test_create_vpn_connection(request_type, transport: str = 'grpc'): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_vpn_connection), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.create_vpn_connection(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = service.CreateVpnConnectionRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_create_vpn_connection_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 = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = service.CreateVpnConnectionRequest( - parent='parent_value', - vpn_connection_id='vpn_connection_id_value', - request_id='request_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_vpn_connection), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_vpn_connection(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.CreateVpnConnectionRequest( - parent='parent_value', - vpn_connection_id='vpn_connection_id_value', - request_id='request_id_value', - ) - -def test_create_vpn_connection_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = EdgeContainerClient( - 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_vpn_connection in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_vpn_connection] = mock_rpc - request = {} - client.create_vpn_connection(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_vpn_connection(request) - - # Establish that 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_vpn_connection_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 = EdgeContainerAsyncClient( - 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_vpn_connection 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_vpn_connection] = mock_rpc - - request = {} - await client.create_vpn_connection(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_vpn_connection(request) - - # Establish that 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_vpn_connection_async(transport: str = 'grpc_asyncio', request_type=service.CreateVpnConnectionRequest): - client = EdgeContainerAsyncClient( - 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_vpn_connection), - '__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_vpn_connection(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = service.CreateVpnConnectionRequest() - 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_vpn_connection_async_from_dict(): - await test_create_vpn_connection_async(request_type=dict) - -def test_create_vpn_connection_field_headers(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.CreateVpnConnectionRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_vpn_connection), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_vpn_connection(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_create_vpn_connection_field_headers_async(): - client = EdgeContainerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.CreateVpnConnectionRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_vpn_connection), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.create_vpn_connection(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_create_vpn_connection_flattened(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_vpn_connection), - '__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_vpn_connection( - parent='parent_value', - vpn_connection=resources.VpnConnection(name='name_value'), - vpn_connection_id='vpn_connection_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].vpn_connection - mock_val = resources.VpnConnection(name='name_value') - assert arg == mock_val - arg = args[0].vpn_connection_id - mock_val = 'vpn_connection_id_value' - assert arg == mock_val - - -def test_create_vpn_connection_flattened_error(): - client = EdgeContainerClient( - 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_vpn_connection( - service.CreateVpnConnectionRequest(), - parent='parent_value', - vpn_connection=resources.VpnConnection(name='name_value'), - vpn_connection_id='vpn_connection_id_value', - ) - -@pytest.mark.asyncio -async def test_create_vpn_connection_flattened_async(): - client = EdgeContainerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_vpn_connection), - '__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_vpn_connection( - parent='parent_value', - vpn_connection=resources.VpnConnection(name='name_value'), - vpn_connection_id='vpn_connection_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].vpn_connection - mock_val = resources.VpnConnection(name='name_value') - assert arg == mock_val - arg = args[0].vpn_connection_id - mock_val = 'vpn_connection_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_vpn_connection_flattened_error_async(): - client = EdgeContainerAsyncClient( - 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_vpn_connection( - service.CreateVpnConnectionRequest(), - parent='parent_value', - vpn_connection=resources.VpnConnection(name='name_value'), - vpn_connection_id='vpn_connection_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - service.DeleteVpnConnectionRequest, - dict, -]) -def test_delete_vpn_connection(request_type, transport: str = 'grpc'): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_vpn_connection), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.delete_vpn_connection(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = service.DeleteVpnConnectionRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_delete_vpn_connection_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 = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = service.DeleteVpnConnectionRequest( - name='name_value', - request_id='request_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_vpn_connection), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.delete_vpn_connection(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.DeleteVpnConnectionRequest( - name='name_value', - request_id='request_id_value', - ) - -def test_delete_vpn_connection_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = EdgeContainerClient( - 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_vpn_connection in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_vpn_connection] = mock_rpc - request = {} - client.delete_vpn_connection(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_vpn_connection(request) - - # Establish that 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_vpn_connection_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 = EdgeContainerAsyncClient( - 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_vpn_connection 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_vpn_connection] = mock_rpc - - request = {} - await client.delete_vpn_connection(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_vpn_connection(request) - - # Establish that 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_vpn_connection_async(transport: str = 'grpc_asyncio', request_type=service.DeleteVpnConnectionRequest): - client = EdgeContainerAsyncClient( - 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_vpn_connection), - '__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_vpn_connection(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = service.DeleteVpnConnectionRequest() - 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_vpn_connection_async_from_dict(): - await test_delete_vpn_connection_async(request_type=dict) - -def test_delete_vpn_connection_field_headers(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.DeleteVpnConnectionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_vpn_connection), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_vpn_connection(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_delete_vpn_connection_field_headers_async(): - client = EdgeContainerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.DeleteVpnConnectionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_vpn_connection), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.delete_vpn_connection(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -def test_delete_vpn_connection_flattened(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_vpn_connection), - '__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_vpn_connection( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_delete_vpn_connection_flattened_error(): - client = EdgeContainerClient( - 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_vpn_connection( - service.DeleteVpnConnectionRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_vpn_connection_flattened_async(): - client = EdgeContainerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_vpn_connection), - '__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_vpn_connection( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_delete_vpn_connection_flattened_error_async(): - client = EdgeContainerAsyncClient( - 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_vpn_connection( - service.DeleteVpnConnectionRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - service.GetServerConfigRequest, - dict, -]) -def test_get_server_config(request_type, transport: str = 'grpc'): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_server_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.ServerConfig( - default_version='default_version_value', - ) - response = client.get_server_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = service.GetServerConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.ServerConfig) - assert response.default_version == 'default_version_value' - - -def test_get_server_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 = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = service.GetServerConfigRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_server_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_server_config(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.GetServerConfigRequest( - name='name_value', - ) - -def test_get_server_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 = EdgeContainerClient( - 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_server_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_server_config] = mock_rpc - request = {} - client.get_server_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_server_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_server_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 = EdgeContainerAsyncClient( - 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_server_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_server_config] = mock_rpc - - request = {} - await client.get_server_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_server_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_server_config_async(transport: str = 'grpc_asyncio', request_type=service.GetServerConfigRequest): - client = EdgeContainerAsyncClient( - 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_server_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.ServerConfig( - default_version='default_version_value', - )) - response = await client.get_server_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = service.GetServerConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.ServerConfig) - assert response.default_version == 'default_version_value' - - -@pytest.mark.asyncio -async def test_get_server_config_async_from_dict(): - await test_get_server_config_async(request_type=dict) - -def test_get_server_config_field_headers(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.GetServerConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_server_config), - '__call__') as call: - call.return_value = resources.ServerConfig() - client.get_server_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', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_server_config_field_headers_async(): - client = EdgeContainerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.GetServerConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_server_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.ServerConfig()) - await client.get_server_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', - 'name=name_value', - ) in kw['metadata'] - - -def test_get_server_config_flattened(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_server_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.ServerConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_server_config( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_get_server_config_flattened_error(): - client = EdgeContainerClient( - 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_server_config( - service.GetServerConfigRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_server_config_flattened_async(): - client = EdgeContainerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_server_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.ServerConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.ServerConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_server_config( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_server_config_flattened_error_async(): - client = EdgeContainerAsyncClient( - 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_server_config( - service.GetServerConfigRequest(), - name='name_value', - ) - - -def test_list_clusters_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = EdgeContainerClient( - 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_clusters in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_clusters] = mock_rpc - - request = {} - client.list_clusters(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_clusters(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_list_clusters_rest_required_fields(request_type=service.ListClustersRequest): - transport_class = transports.EdgeContainerRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_clusters._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_clusters._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("filter", "order_by", "page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = service.ListClustersResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = service.ListClustersResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_clusters(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_clusters_rest_unset_required_fields(): - transport = transports.EdgeContainerRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_clusters._get_unset_required_fields({}) - assert set(unset_fields) == (set(("filter", "orderBy", "pageSize", "pageToken", )) & set(("parent", ))) - - -def test_list_clusters_rest_flattened(): - client = EdgeContainerClient( - 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.ListClustersResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = service.ListClustersResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_clusters(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{parent=projects/*/locations/*}/clusters" % client.transport._host, args[1]) - - -def test_list_clusters_rest_flattened_error(transport: str = 'rest'): - client = EdgeContainerClient( - 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_clusters( - service.ListClustersRequest(), - parent='parent_value', - ) - - -def test_list_clusters_rest_pager(transport: str = 'rest'): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - #with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - service.ListClustersResponse( - clusters=[ - resources.Cluster(), - resources.Cluster(), - resources.Cluster(), - ], - next_page_token='abc', - ), - service.ListClustersResponse( - clusters=[], - next_page_token='def', - ), - service.ListClustersResponse( - clusters=[ - resources.Cluster(), - ], - next_page_token='ghi', - ), - service.ListClustersResponse( - clusters=[ - resources.Cluster(), - resources.Cluster(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(service.ListClustersResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode('UTF-8') - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {'parent': 'projects/sample1/locations/sample2'} - - pager = client.list_clusters(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, resources.Cluster) - for i in results) - - pages = list(client.list_clusters(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_get_cluster_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = EdgeContainerClient( - 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_cluster in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_cluster] = mock_rpc - - request = {} - client.get_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_cluster(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_get_cluster_rest_required_fields(request_type=service.GetClusterRequest): - transport_class = transports.EdgeContainerRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_cluster._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_cluster._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = resources.Cluster() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # 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.Cluster.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_cluster(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_cluster_rest_unset_required_fields(): - transport = transports.EdgeContainerRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_cluster._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_get_cluster_rest_flattened(): - client = EdgeContainerClient( - 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.Cluster() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/clusters/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = resources.Cluster.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_cluster(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=projects/*/locations/*/clusters/*}" % client.transport._host, args[1]) - - -def test_get_cluster_rest_flattened_error(transport: str = 'rest'): - client = EdgeContainerClient( - 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_cluster( - service.GetClusterRequest(), - name='name_value', - ) - - -def test_create_cluster_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = EdgeContainerClient( - 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_cluster in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.create_cluster] = mock_rpc - - request = {} - client.create_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.create_cluster(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_create_cluster_rest_required_fields(request_type=service.CreateClusterRequest): - transport_class = transports.EdgeContainerRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["cluster_id"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - assert "clusterId" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_cluster._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "clusterId" in jsonified_request - assert jsonified_request["clusterId"] == request_init["cluster_id"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["clusterId"] = 'cluster_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_cluster._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("cluster_id", "request_id", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - assert "clusterId" in jsonified_request - assert jsonified_request["clusterId"] == 'cluster_id_value' - - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.create_cluster(request) - - expected_params = [ - ( - "clusterId", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_cluster_rest_unset_required_fields(): - transport = transports.EdgeContainerRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_cluster._get_unset_required_fields({}) - assert set(unset_fields) == (set(("clusterId", "requestId", )) & set(("parent", "clusterId", "cluster", ))) - - -def test_create_cluster_rest_flattened(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - cluster=resources.Cluster(name='name_value'), - cluster_id='cluster_id_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.create_cluster(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{parent=projects/*/locations/*}/clusters" % client.transport._host, args[1]) - - -def test_create_cluster_rest_flattened_error(transport: str = 'rest'): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_cluster( - service.CreateClusterRequest(), - parent='parent_value', - cluster=resources.Cluster(name='name_value'), - cluster_id='cluster_id_value', - ) - - -def test_update_cluster_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.update_cluster in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_cluster] = mock_rpc - - request = {} - client.update_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.update_cluster(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_update_cluster_rest_flattened(): - client = EdgeContainerClient( - 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 = {'cluster': {'name': 'projects/sample1/locations/sample2/clusters/sample3'}} - - # get truthy value for each flattened field - mock_args = dict( - cluster=resources.Cluster(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.update_cluster(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{cluster.name=projects/*/locations/*/clusters/*}" % client.transport._host, args[1]) - - -def test_update_cluster_rest_flattened_error(transport: str = 'rest'): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.update_cluster( - service.UpdateClusterRequest(), - cluster=resources.Cluster(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_upgrade_cluster_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = EdgeContainerClient( - 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.upgrade_cluster in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.upgrade_cluster] = mock_rpc - - request = {} - client.upgrade_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.upgrade_cluster(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_upgrade_cluster_rest_required_fields(request_type=service.UpgradeClusterRequest): - transport_class = transports.EdgeContainerRestTransport - - request_init = {} - request_init["name"] = "" - request_init["target_version"] = "" - 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()).upgrade_cluster._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - jsonified_request["targetVersion"] = 'target_version_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).upgrade_cluster._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - assert "targetVersion" in jsonified_request - assert jsonified_request["targetVersion"] == 'target_version_value' - - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.upgrade_cluster(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_upgrade_cluster_rest_unset_required_fields(): - transport = transports.EdgeContainerRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.upgrade_cluster._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", "targetVersion", ))) - - -def test_upgrade_cluster_rest_flattened(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/clusters/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - target_version='target_version_value', - schedule=service.UpgradeClusterRequest.Schedule.IMMEDIATELY, - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.upgrade_cluster(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=projects/*/locations/*/clusters/*}:upgrade" % client.transport._host, args[1]) - - -def test_upgrade_cluster_rest_flattened_error(transport: str = 'rest'): - client = EdgeContainerClient( - 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.upgrade_cluster( - service.UpgradeClusterRequest(), - name='name_value', - target_version='target_version_value', - schedule=service.UpgradeClusterRequest.Schedule.IMMEDIATELY, - ) - - -def test_delete_cluster_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = EdgeContainerClient( - 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_cluster in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.delete_cluster] = mock_rpc - - request = {} - client.delete_cluster(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.delete_cluster(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_delete_cluster_rest_required_fields(request_type=service.DeleteClusterRequest): - transport_class = transports.EdgeContainerRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_cluster._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_cluster._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("request_id", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "delete", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.delete_cluster(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_cluster_rest_unset_required_fields(): - transport = transports.EdgeContainerRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_cluster._get_unset_required_fields({}) - assert set(unset_fields) == (set(("requestId", )) & set(("name", ))) - - -def test_delete_cluster_rest_flattened(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/clusters/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.delete_cluster(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=projects/*/locations/*/clusters/*}" % client.transport._host, args[1]) - - -def test_delete_cluster_rest_flattened_error(transport: str = 'rest'): - client = EdgeContainerClient( - 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_cluster( - service.DeleteClusterRequest(), - name='name_value', - ) - - -def test_generate_access_token_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 = EdgeContainerClient( - 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_access_token in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_access_token] = mock_rpc - - request = {} - client.generate_access_token(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.generate_access_token(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_access_token_rest_required_fields(request_type=service.GenerateAccessTokenRequest): - transport_class = transports.EdgeContainerRestTransport - - request_init = {} - request_init["cluster"] = "" - 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_access_token._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["cluster"] = 'cluster_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).generate_access_token._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "cluster" in jsonified_request - assert jsonified_request["cluster"] == 'cluster_value' - - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = service.GenerateAccessTokenResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = service.GenerateAccessTokenResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.generate_access_token(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_generate_access_token_rest_unset_required_fields(): - transport = transports.EdgeContainerRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.generate_access_token._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("cluster", ))) - - -def test_generate_access_token_rest_flattened(): - client = EdgeContainerClient( - 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.GenerateAccessTokenResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'cluster': 'projects/sample1/locations/sample2/clusters/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - cluster='cluster_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = service.GenerateAccessTokenResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.generate_access_token(**mock_args) - - # Establish that the underlying call 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/{cluster=projects/*/locations/*/clusters/*}:generateAccessToken" % client.transport._host, args[1]) - - -def test_generate_access_token_rest_flattened_error(transport: str = 'rest'): - client = EdgeContainerClient( - 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_access_token( - service.GenerateAccessTokenRequest(), - cluster='cluster_value', - ) - - -def test_generate_offline_credential_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 = EdgeContainerClient( - 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_offline_credential in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_offline_credential] = mock_rpc - - request = {} - client.generate_offline_credential(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.generate_offline_credential(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_offline_credential_rest_required_fields(request_type=service.GenerateOfflineCredentialRequest): - transport_class = transports.EdgeContainerRestTransport - - request_init = {} - request_init["cluster"] = "" - 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_offline_credential._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["cluster"] = 'cluster_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).generate_offline_credential._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "cluster" in jsonified_request - assert jsonified_request["cluster"] == 'cluster_value' - - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = service.GenerateOfflineCredentialResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = service.GenerateOfflineCredentialResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.generate_offline_credential(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_generate_offline_credential_rest_unset_required_fields(): - transport = transports.EdgeContainerRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.generate_offline_credential._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("cluster", ))) - - -def test_generate_offline_credential_rest_flattened(): - client = EdgeContainerClient( - 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.GenerateOfflineCredentialResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'cluster': 'projects/sample1/locations/sample2/clusters/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - cluster='cluster_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = service.GenerateOfflineCredentialResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.generate_offline_credential(**mock_args) - - # Establish that the underlying call 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/{cluster=projects/*/locations/*/clusters/*}:generateOfflineCredential" % client.transport._host, args[1]) - - -def test_generate_offline_credential_rest_flattened_error(transport: str = 'rest'): - client = EdgeContainerClient( - 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_offline_credential( - service.GenerateOfflineCredentialRequest(), - cluster='cluster_value', - ) - - -def test_list_node_pools_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 = EdgeContainerClient( - 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_node_pools in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_node_pools] = mock_rpc - - request = {} - client.list_node_pools(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_node_pools(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_node_pools_rest_required_fields(request_type=service.ListNodePoolsRequest): - transport_class = transports.EdgeContainerRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_node_pools._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_node_pools._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("filter", "order_by", "page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = service.ListNodePoolsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = service.ListNodePoolsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_node_pools(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_node_pools_rest_unset_required_fields(): - transport = transports.EdgeContainerRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_node_pools._get_unset_required_fields({}) - assert set(unset_fields) == (set(("filter", "orderBy", "pageSize", "pageToken", )) & set(("parent", ))) - - -def test_list_node_pools_rest_flattened(): - client = EdgeContainerClient( - 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.ListNodePoolsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = service.ListNodePoolsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_node_pools(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{parent=projects/*/locations/*/clusters/*}/nodePools" % client.transport._host, args[1]) - - -def test_list_node_pools_rest_flattened_error(transport: str = 'rest'): - client = EdgeContainerClient( - 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_node_pools( - service.ListNodePoolsRequest(), - parent='parent_value', - ) - - -def test_list_node_pools_rest_pager(transport: str = 'rest'): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - #with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - service.ListNodePoolsResponse( - node_pools=[ - resources.NodePool(), - resources.NodePool(), - resources.NodePool(), - ], - next_page_token='abc', - ), - service.ListNodePoolsResponse( - node_pools=[], - next_page_token='def', - ), - service.ListNodePoolsResponse( - node_pools=[ - resources.NodePool(), - ], - next_page_token='ghi', - ), - service.ListNodePoolsResponse( - node_pools=[ - resources.NodePool(), - resources.NodePool(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(service.ListNodePoolsResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode('UTF-8') - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} - - pager = client.list_node_pools(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, resources.NodePool) - for i in results) - - pages = list(client.list_node_pools(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_get_node_pool_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 = EdgeContainerClient( - 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_node_pool in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_node_pool] = mock_rpc - - request = {} - client.get_node_pool(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_node_pool(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_node_pool_rest_required_fields(request_type=service.GetNodePoolRequest): - transport_class = transports.EdgeContainerRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_node_pool._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_node_pool._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = resources.NodePool() - # Mock the http request call 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.NodePool.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_node_pool(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_node_pool_rest_unset_required_fields(): - transport = transports.EdgeContainerRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_node_pool._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_get_node_pool_rest_flattened(): - client = EdgeContainerClient( - 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.NodePool() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/clusters/sample3/nodePools/sample4'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = resources.NodePool.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_node_pool(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=projects/*/locations/*/clusters/*/nodePools/*}" % client.transport._host, args[1]) - - -def test_get_node_pool_rest_flattened_error(transport: str = 'rest'): - client = EdgeContainerClient( - 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_node_pool( - service.GetNodePoolRequest(), - name='name_value', - ) - - -def test_create_node_pool_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 = EdgeContainerClient( - 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_node_pool in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_node_pool] = mock_rpc - - request = {} - client.create_node_pool(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_node_pool(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_node_pool_rest_required_fields(request_type=service.CreateNodePoolRequest): - transport_class = transports.EdgeContainerRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["node_pool_id"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - assert "nodePoolId" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_node_pool._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "nodePoolId" in jsonified_request - assert jsonified_request["nodePoolId"] == request_init["node_pool_id"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["nodePoolId"] = 'node_pool_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_node_pool._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("node_pool_id", "request_id", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - assert "nodePoolId" in jsonified_request - assert jsonified_request["nodePoolId"] == 'node_pool_id_value' - - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.create_node_pool(request) - - expected_params = [ - ( - "nodePoolId", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_node_pool_rest_unset_required_fields(): - transport = transports.EdgeContainerRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_node_pool._get_unset_required_fields({}) - assert set(unset_fields) == (set(("nodePoolId", "requestId", )) & set(("parent", "nodePoolId", "nodePool", ))) - - -def test_create_node_pool_rest_flattened(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - node_pool=resources.NodePool(name='name_value'), - node_pool_id='node_pool_id_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.create_node_pool(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{parent=projects/*/locations/*/clusters/*}/nodePools" % client.transport._host, args[1]) - - -def test_create_node_pool_rest_flattened_error(transport: str = 'rest'): - client = EdgeContainerClient( - 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_node_pool( - service.CreateNodePoolRequest(), - parent='parent_value', - node_pool=resources.NodePool(name='name_value'), - node_pool_id='node_pool_id_value', - ) - - -def test_update_node_pool_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 = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.update_node_pool in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_node_pool] = mock_rpc - - request = {} - client.update_node_pool(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.update_node_pool(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_update_node_pool_rest_flattened(): - client = EdgeContainerClient( - 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 = {'node_pool': {'name': 'projects/sample1/locations/sample2/clusters/sample3/nodePools/sample4'}} - - # get truthy value for each flattened field - mock_args = dict( - node_pool=resources.NodePool(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.update_node_pool(**mock_args) - - # Establish that the underlying call 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/{node_pool.name=projects/*/locations/*/clusters/*/nodePools/*}" % client.transport._host, args[1]) - - -def test_update_node_pool_rest_flattened_error(transport: str = 'rest'): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.update_node_pool( - service.UpdateNodePoolRequest(), - node_pool=resources.NodePool(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_delete_node_pool_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 = EdgeContainerClient( - 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_node_pool in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_node_pool] = mock_rpc - - request = {} - client.delete_node_pool(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_node_pool(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_node_pool_rest_required_fields(request_type=service.DeleteNodePoolRequest): - transport_class = transports.EdgeContainerRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_node_pool._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_node_pool._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("request_id", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "delete", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.delete_node_pool(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_node_pool_rest_unset_required_fields(): - transport = transports.EdgeContainerRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_node_pool._get_unset_required_fields({}) - assert set(unset_fields) == (set(("requestId", )) & set(("name", ))) - - -def test_delete_node_pool_rest_flattened(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/clusters/sample3/nodePools/sample4'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.delete_node_pool(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=projects/*/locations/*/clusters/*/nodePools/*}" % client.transport._host, args[1]) - - -def test_delete_node_pool_rest_flattened_error(transport: str = 'rest'): - client = EdgeContainerClient( - 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_node_pool( - service.DeleteNodePoolRequest(), - name='name_value', - ) - - -def test_list_machines_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 = EdgeContainerClient( - 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_machines in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_machines] = mock_rpc - - request = {} - client.list_machines(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_machines(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_machines_rest_required_fields(request_type=service.ListMachinesRequest): - transport_class = transports.EdgeContainerRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_machines._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_machines._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("filter", "order_by", "page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = service.ListMachinesResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = service.ListMachinesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_machines(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_machines_rest_unset_required_fields(): - transport = transports.EdgeContainerRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_machines._get_unset_required_fields({}) - assert set(unset_fields) == (set(("filter", "orderBy", "pageSize", "pageToken", )) & set(("parent", ))) - - -def test_list_machines_rest_flattened(): - client = EdgeContainerClient( - 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.ListMachinesResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = service.ListMachinesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_machines(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{parent=projects/*/locations/*}/machines" % client.transport._host, args[1]) - - -def test_list_machines_rest_flattened_error(transport: str = 'rest'): - client = EdgeContainerClient( - 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_machines( - service.ListMachinesRequest(), - parent='parent_value', - ) - - -def test_list_machines_rest_pager(transport: str = 'rest'): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - #with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - service.ListMachinesResponse( - machines=[ - resources.Machine(), - resources.Machine(), - resources.Machine(), - ], - next_page_token='abc', - ), - service.ListMachinesResponse( - machines=[], - next_page_token='def', - ), - service.ListMachinesResponse( - machines=[ - resources.Machine(), - ], - next_page_token='ghi', - ), - service.ListMachinesResponse( - machines=[ - resources.Machine(), - resources.Machine(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(service.ListMachinesResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode('UTF-8') - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {'parent': 'projects/sample1/locations/sample2'} - - pager = client.list_machines(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, resources.Machine) - for i in results) - - pages = list(client.list_machines(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_get_machine_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 = EdgeContainerClient( - 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_machine in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_machine] = mock_rpc - - request = {} - client.get_machine(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_machine(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_machine_rest_required_fields(request_type=service.GetMachineRequest): - transport_class = transports.EdgeContainerRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_machine._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_machine._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = resources.Machine() - # Mock the http request call 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.Machine.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_machine(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_machine_rest_unset_required_fields(): - transport = transports.EdgeContainerRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_machine._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_get_machine_rest_flattened(): - client = EdgeContainerClient( - 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.Machine() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/machines/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = resources.Machine.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_machine(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=projects/*/locations/*/machines/*}" % client.transport._host, args[1]) - - -def test_get_machine_rest_flattened_error(transport: str = 'rest'): - client = EdgeContainerClient( - 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_machine( - service.GetMachineRequest(), - name='name_value', - ) - - -def test_list_vpn_connections_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 = EdgeContainerClient( - 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_vpn_connections in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_vpn_connections] = mock_rpc - - request = {} - client.list_vpn_connections(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_vpn_connections(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_vpn_connections_rest_required_fields(request_type=service.ListVpnConnectionsRequest): - transport_class = transports.EdgeContainerRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_vpn_connections._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_vpn_connections._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("filter", "order_by", "page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = service.ListVpnConnectionsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = service.ListVpnConnectionsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_vpn_connections(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_vpn_connections_rest_unset_required_fields(): - transport = transports.EdgeContainerRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_vpn_connections._get_unset_required_fields({}) - assert set(unset_fields) == (set(("filter", "orderBy", "pageSize", "pageToken", )) & set(("parent", ))) - - -def test_list_vpn_connections_rest_flattened(): - client = EdgeContainerClient( - 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.ListVpnConnectionsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = service.ListVpnConnectionsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_vpn_connections(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{parent=projects/*/locations/*}/vpnConnections" % client.transport._host, args[1]) - - -def test_list_vpn_connections_rest_flattened_error(transport: str = 'rest'): - client = EdgeContainerClient( - 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_vpn_connections( - service.ListVpnConnectionsRequest(), - parent='parent_value', - ) - - -def test_list_vpn_connections_rest_pager(transport: str = 'rest'): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - #with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - service.ListVpnConnectionsResponse( - vpn_connections=[ - resources.VpnConnection(), - resources.VpnConnection(), - resources.VpnConnection(), - ], - next_page_token='abc', - ), - service.ListVpnConnectionsResponse( - vpn_connections=[], - next_page_token='def', - ), - service.ListVpnConnectionsResponse( - vpn_connections=[ - resources.VpnConnection(), - ], - next_page_token='ghi', - ), - service.ListVpnConnectionsResponse( - vpn_connections=[ - resources.VpnConnection(), - resources.VpnConnection(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(service.ListVpnConnectionsResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode('UTF-8') - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {'parent': 'projects/sample1/locations/sample2'} - - pager = client.list_vpn_connections(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, resources.VpnConnection) - for i in results) - - pages = list(client.list_vpn_connections(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_get_vpn_connection_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 = EdgeContainerClient( - 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_vpn_connection in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_vpn_connection] = mock_rpc - - request = {} - client.get_vpn_connection(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_vpn_connection(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_vpn_connection_rest_required_fields(request_type=service.GetVpnConnectionRequest): - transport_class = transports.EdgeContainerRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_vpn_connection._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_vpn_connection._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = resources.VpnConnection() - # Mock the http request call 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.VpnConnection.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_vpn_connection(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_vpn_connection_rest_unset_required_fields(): - transport = transports.EdgeContainerRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_vpn_connection._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_get_vpn_connection_rest_flattened(): - client = EdgeContainerClient( - 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.VpnConnection() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/vpnConnections/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = resources.VpnConnection.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_vpn_connection(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=projects/*/locations/*/vpnConnections/*}" % client.transport._host, args[1]) - - -def test_get_vpn_connection_rest_flattened_error(transport: str = 'rest'): - client = EdgeContainerClient( - 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_vpn_connection( - service.GetVpnConnectionRequest(), - name='name_value', - ) - - -def test_create_vpn_connection_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 = EdgeContainerClient( - 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_vpn_connection in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_vpn_connection] = mock_rpc - - request = {} - client.create_vpn_connection(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_vpn_connection(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_vpn_connection_rest_required_fields(request_type=service.CreateVpnConnectionRequest): - transport_class = transports.EdgeContainerRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["vpn_connection_id"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - assert "vpnConnectionId" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_vpn_connection._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "vpnConnectionId" in jsonified_request - assert jsonified_request["vpnConnectionId"] == request_init["vpn_connection_id"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["vpnConnectionId"] = 'vpn_connection_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_vpn_connection._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("request_id", "vpn_connection_id", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - assert "vpnConnectionId" in jsonified_request - assert jsonified_request["vpnConnectionId"] == 'vpn_connection_id_value' - - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.create_vpn_connection(request) - - expected_params = [ - ( - "vpnConnectionId", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_vpn_connection_rest_unset_required_fields(): - transport = transports.EdgeContainerRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_vpn_connection._get_unset_required_fields({}) - assert set(unset_fields) == (set(("requestId", "vpnConnectionId", )) & set(("parent", "vpnConnectionId", "vpnConnection", ))) - - -def test_create_vpn_connection_rest_flattened(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - vpn_connection=resources.VpnConnection(name='name_value'), - vpn_connection_id='vpn_connection_id_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.create_vpn_connection(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{parent=projects/*/locations/*}/vpnConnections" % client.transport._host, args[1]) - - -def test_create_vpn_connection_rest_flattened_error(transport: str = 'rest'): - client = EdgeContainerClient( - 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_vpn_connection( - service.CreateVpnConnectionRequest(), - parent='parent_value', - vpn_connection=resources.VpnConnection(name='name_value'), - vpn_connection_id='vpn_connection_id_value', - ) - - -def test_delete_vpn_connection_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 = EdgeContainerClient( - 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_vpn_connection in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = 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_vpn_connection] = mock_rpc - - request = {} - client.delete_vpn_connection(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_vpn_connection(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_vpn_connection_rest_required_fields(request_type=service.DeleteVpnConnectionRequest): - transport_class = transports.EdgeContainerRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_vpn_connection._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_vpn_connection._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("request_id", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "delete", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.delete_vpn_connection(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_vpn_connection_rest_unset_required_fields(): - transport = transports.EdgeContainerRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_vpn_connection._get_unset_required_fields({}) - assert set(unset_fields) == (set(("requestId", )) & set(("name", ))) - - -def test_delete_vpn_connection_rest_flattened(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/vpnConnections/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.delete_vpn_connection(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=projects/*/locations/*/vpnConnections/*}" % client.transport._host, args[1]) - - -def test_delete_vpn_connection_rest_flattened_error(transport: str = 'rest'): - client = EdgeContainerClient( - 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_vpn_connection( - service.DeleteVpnConnectionRequest(), - name='name_value', - ) - - -def test_get_server_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 = EdgeContainerClient( - 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_server_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_server_config] = mock_rpc - - request = {} - client.get_server_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_server_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_server_config_rest_required_fields(request_type=service.GetServerConfigRequest): - transport_class = transports.EdgeContainerRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_server_config._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_server_config._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = resources.ServerConfig() - # Mock the http request call 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.ServerConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_server_config(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_server_config_rest_unset_required_fields(): - transport = transports.EdgeContainerRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_server_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_get_server_config_rest_flattened(): - client = EdgeContainerClient( - 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.ServerConfig() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = resources.ServerConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_server_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/{name=projects/*/locations/*}/serverConfig" % client.transport._host, args[1]) - - -def test_get_server_config_rest_flattened_error(transport: str = 'rest'): - client = EdgeContainerClient( - 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_server_config( - service.GetServerConfigRequest(), - name='name_value', - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.EdgeContainerGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.EdgeContainerGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = EdgeContainerClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.EdgeContainerGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = EdgeContainerClient( - 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 = EdgeContainerClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.EdgeContainerGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = EdgeContainerClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.EdgeContainerGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = EdgeContainerClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.EdgeContainerGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.EdgeContainerGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.EdgeContainerGrpcTransport, - transports.EdgeContainerGrpcAsyncIOTransport, - transports.EdgeContainerRestTransport, -]) -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 = EdgeContainerClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" - - -def test_initialize_client_w_grpc(): - client = EdgeContainerClient( - 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_clusters_empty_call_grpc(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_clusters), - '__call__') as call: - call.return_value = service.ListClustersResponse() - client.list_clusters(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.ListClustersRequest() - - assert args[0] == request_msg - - -# This 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_cluster_empty_call_grpc(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_cluster), - '__call__') as call: - call.return_value = resources.Cluster() - client.get_cluster(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.GetClusterRequest() - - assert args[0] == request_msg - - -# This 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_cluster_empty_call_grpc(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_cluster), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_cluster(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.CreateClusterRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_update_cluster_empty_call_grpc(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_cluster), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_cluster(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.UpdateClusterRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_upgrade_cluster_empty_call_grpc(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.upgrade_cluster), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.upgrade_cluster(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.UpgradeClusterRequest() - - assert args[0] == request_msg - - -# This 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_cluster_empty_call_grpc(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_cluster), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_cluster(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.DeleteClusterRequest() - - assert args[0] == request_msg - - -# This 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_access_token_empty_call_grpc(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.generate_access_token), - '__call__') as call: - call.return_value = service.GenerateAccessTokenResponse() - client.generate_access_token(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.GenerateAccessTokenRequest() - - assert args[0] == request_msg - - -# This 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_offline_credential_empty_call_grpc(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.generate_offline_credential), - '__call__') as call: - call.return_value = service.GenerateOfflineCredentialResponse() - client.generate_offline_credential(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.GenerateOfflineCredentialRequest() - - assert args[0] == request_msg - - -# This 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_node_pools_empty_call_grpc(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_node_pools), - '__call__') as call: - call.return_value = service.ListNodePoolsResponse() - client.list_node_pools(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.ListNodePoolsRequest() - - assert args[0] == request_msg - - -# This 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_node_pool_empty_call_grpc(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_node_pool), - '__call__') as call: - call.return_value = resources.NodePool() - client.get_node_pool(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.GetNodePoolRequest() - - assert args[0] == request_msg - - -# This 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_node_pool_empty_call_grpc(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_node_pool), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_node_pool(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.CreateNodePoolRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_update_node_pool_empty_call_grpc(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_node_pool), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.update_node_pool(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.UpdateNodePoolRequest() - - assert args[0] == request_msg - - -# This 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_node_pool_empty_call_grpc(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_node_pool), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_node_pool(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.DeleteNodePoolRequest() - - assert args[0] == request_msg - - -# This 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_machines_empty_call_grpc(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_machines), - '__call__') as call: - call.return_value = service.ListMachinesResponse() - client.list_machines(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.ListMachinesRequest() - - assert args[0] == request_msg - - -# This 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_machine_empty_call_grpc(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_machine), - '__call__') as call: - call.return_value = resources.Machine() - client.get_machine(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.GetMachineRequest() - - assert args[0] == request_msg - - -# This 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_vpn_connections_empty_call_grpc(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_vpn_connections), - '__call__') as call: - call.return_value = service.ListVpnConnectionsResponse() - client.list_vpn_connections(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.ListVpnConnectionsRequest() - - assert args[0] == request_msg - - -# This 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_vpn_connection_empty_call_grpc(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_vpn_connection), - '__call__') as call: - call.return_value = resources.VpnConnection() - client.get_vpn_connection(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.GetVpnConnectionRequest() - - assert args[0] == request_msg - - -# This 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_vpn_connection_empty_call_grpc(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_vpn_connection), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_vpn_connection(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.CreateVpnConnectionRequest() - - assert args[0] == request_msg - - -# This 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_vpn_connection_empty_call_grpc(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_vpn_connection), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_vpn_connection(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.DeleteVpnConnectionRequest() - - assert args[0] == request_msg - - -# This 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_server_config_empty_call_grpc(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_server_config), - '__call__') as call: - call.return_value = resources.ServerConfig() - client.get_server_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.GetServerConfigRequest() - - assert args[0] == request_msg - - -def test_transport_kind_grpc_asyncio(): - transport = EdgeContainerAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" - - -def test_initialize_client_w_grpc_asyncio(): - client = EdgeContainerAsyncClient( - 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_clusters_empty_call_grpc_asyncio(): - client = EdgeContainerAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_clusters), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.ListClustersResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - )) - await client.list_clusters(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.ListClustersRequest() - - assert args[0] == request_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_cluster_empty_call_grpc_asyncio(): - client = EdgeContainerAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_cluster), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Cluster( - name='name_value', - default_max_pods_per_node=2634, - endpoint='endpoint_value', - port=453, - cluster_ca_certificate='cluster_ca_certificate_value', - control_plane_version='control_plane_version_value', - node_version='node_version_value', - external_load_balancer_ipv4_address_pools=['external_load_balancer_ipv4_address_pools_value'], - status=resources.Cluster.Status.PROVISIONING, - target_version='target_version_value', - release_channel=resources.Cluster.ReleaseChannel.NONE, - external_load_balancer_ipv6_address_pools=['external_load_balancer_ipv6_address_pools_value'], - )) - await client.get_cluster(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.GetClusterRequest() - - assert args[0] == request_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_cluster_empty_call_grpc_asyncio(): - client = EdgeContainerAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_cluster), - '__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_cluster(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.CreateClusterRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_update_cluster_empty_call_grpc_asyncio(): - client = EdgeContainerAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_cluster), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - await client.update_cluster(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.UpdateClusterRequest() - - assert args[0] == request_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_upgrade_cluster_empty_call_grpc_asyncio(): - client = EdgeContainerAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.upgrade_cluster), - '__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.upgrade_cluster(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.UpgradeClusterRequest() - - assert args[0] == request_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_cluster_empty_call_grpc_asyncio(): - client = EdgeContainerAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_cluster), - '__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_cluster(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.DeleteClusterRequest() - - assert args[0] == request_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_access_token_empty_call_grpc_asyncio(): - client = EdgeContainerAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.generate_access_token), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.GenerateAccessTokenResponse( - access_token='access_token_value', - )) - await client.generate_access_token(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.GenerateAccessTokenRequest() - - assert args[0] == request_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_offline_credential_empty_call_grpc_asyncio(): - client = EdgeContainerAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.generate_offline_credential), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.GenerateOfflineCredentialResponse( - client_certificate='client_certificate_value', - client_key='client_key_value', - user_id='user_id_value', - )) - await client.generate_offline_credential(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.GenerateOfflineCredentialRequest() - - assert args[0] == request_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_node_pools_empty_call_grpc_asyncio(): - client = EdgeContainerAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_node_pools), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.ListNodePoolsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - )) - await client.list_node_pools(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.ListNodePoolsRequest() - - assert args[0] == request_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_node_pool_empty_call_grpc_asyncio(): - client = EdgeContainerAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_node_pool), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.NodePool( - name='name_value', - node_location='node_location_value', - node_count=1070, - machine_filter='machine_filter_value', - node_version='node_version_value', - )) - await client.get_node_pool(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.GetNodePoolRequest() - - assert args[0] == request_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_node_pool_empty_call_grpc_asyncio(): - client = EdgeContainerAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_node_pool), - '__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_node_pool(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.CreateNodePoolRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_update_node_pool_empty_call_grpc_asyncio(): - client = EdgeContainerAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_node_pool), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - await client.update_node_pool(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.UpdateNodePoolRequest() - - assert args[0] == request_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_node_pool_empty_call_grpc_asyncio(): - client = EdgeContainerAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_node_pool), - '__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_node_pool(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.DeleteNodePoolRequest() - - assert args[0] == request_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_machines_empty_call_grpc_asyncio(): - client = EdgeContainerAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_machines), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.ListMachinesResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - )) - await client.list_machines(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.ListMachinesRequest() - - assert args[0] == request_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_machine_empty_call_grpc_asyncio(): - client = EdgeContainerAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_machine), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Machine( - name='name_value', - hosted_node='hosted_node_value', - zone='zone_value', - version='version_value', - disabled=True, - )) - await client.get_machine(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.GetMachineRequest() - - assert args[0] == request_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_vpn_connections_empty_call_grpc_asyncio(): - client = EdgeContainerAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_vpn_connections), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.ListVpnConnectionsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - )) - await client.list_vpn_connections(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.ListVpnConnectionsRequest() - - assert args[0] == request_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_vpn_connection_empty_call_grpc_asyncio(): - client = EdgeContainerAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_vpn_connection), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.VpnConnection( - name='name_value', - nat_gateway_ip='nat_gateway_ip_value', - bgp_routing_mode=resources.VpnConnection.BgpRoutingMode.REGIONAL, - cluster='cluster_value', - vpc='vpc_value', - enable_high_availability=True, - router='router_value', - )) - await client.get_vpn_connection(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.GetVpnConnectionRequest() - - assert args[0] == request_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_vpn_connection_empty_call_grpc_asyncio(): - client = EdgeContainerAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_vpn_connection), - '__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_vpn_connection(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.CreateVpnConnectionRequest() - - assert args[0] == request_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_vpn_connection_empty_call_grpc_asyncio(): - client = EdgeContainerAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_vpn_connection), - '__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_vpn_connection(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.DeleteVpnConnectionRequest() - - assert args[0] == request_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_server_config_empty_call_grpc_asyncio(): - client = EdgeContainerAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_server_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.ServerConfig( - default_version='default_version_value', - )) - await client.get_server_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.GetServerConfigRequest() - - assert args[0] == request_msg - - -def test_transport_kind_rest(): - transport = EdgeContainerClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" - - -def test_list_clusters_rest_bad_request(request_type=service.ListClustersRequest): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - client.list_clusters(request) - - -@pytest.mark.parametrize("request_type", [ - service.ListClustersRequest, - dict, -]) -def test_list_clusters_rest_call_success(request_type): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = service.ListClustersResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = service.ListClustersResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_clusters(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListClustersPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_clusters_rest_interceptors(null_interceptor): - transport = transports.EdgeContainerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EdgeContainerRestInterceptor(), - ) - client = EdgeContainerClient(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.EdgeContainerRestInterceptor, "post_list_clusters") as post, \ - mock.patch.object(transports.EdgeContainerRestInterceptor, "pre_list_clusters") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = service.ListClustersRequest.pb(service.ListClustersRequest()) - 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 - return_value = service.ListClustersResponse.to_json(service.ListClustersResponse()) - req.return_value.content = return_value - - request = service.ListClustersRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = service.ListClustersResponse() - - client.list_clusters(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_cluster_rest_bad_request(request_type=service.GetClusterRequest): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - client.get_cluster(request) - - -@pytest.mark.parametrize("request_type", [ - service.GetClusterRequest, - dict, -]) -def test_get_cluster_rest_call_success(request_type): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = resources.Cluster( - name='name_value', - default_max_pods_per_node=2634, - endpoint='endpoint_value', - port=453, - cluster_ca_certificate='cluster_ca_certificate_value', - control_plane_version='control_plane_version_value', - node_version='node_version_value', - external_load_balancer_ipv4_address_pools=['external_load_balancer_ipv4_address_pools_value'], - status=resources.Cluster.Status.PROVISIONING, - target_version='target_version_value', - release_channel=resources.Cluster.ReleaseChannel.NONE, - external_load_balancer_ipv6_address_pools=['external_load_balancer_ipv6_address_pools_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.Cluster.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_cluster(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.Cluster) - assert response.name == 'name_value' - assert response.default_max_pods_per_node == 2634 - assert response.endpoint == 'endpoint_value' - assert response.port == 453 - assert response.cluster_ca_certificate == 'cluster_ca_certificate_value' - assert response.control_plane_version == 'control_plane_version_value' - assert response.node_version == 'node_version_value' - assert response.external_load_balancer_ipv4_address_pools == ['external_load_balancer_ipv4_address_pools_value'] - assert response.status == resources.Cluster.Status.PROVISIONING - assert response.target_version == 'target_version_value' - assert response.release_channel == resources.Cluster.ReleaseChannel.NONE - assert response.external_load_balancer_ipv6_address_pools == ['external_load_balancer_ipv6_address_pools_value'] - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_cluster_rest_interceptors(null_interceptor): - transport = transports.EdgeContainerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EdgeContainerRestInterceptor(), - ) - client = EdgeContainerClient(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.EdgeContainerRestInterceptor, "post_get_cluster") as post, \ - mock.patch.object(transports.EdgeContainerRestInterceptor, "pre_get_cluster") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = service.GetClusterRequest.pb(service.GetClusterRequest()) - 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 - return_value = resources.Cluster.to_json(resources.Cluster()) - req.return_value.content = return_value - - request = service.GetClusterRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = resources.Cluster() - - client.get_cluster(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_cluster_rest_bad_request(request_type=service.CreateClusterRequest): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - client.create_cluster(request) - - -@pytest.mark.parametrize("request_type", [ - service.CreateClusterRequest, - dict, -]) -def test_create_cluster_rest_call_success(request_type): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request_init["cluster"] = {'name': 'name_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'fleet': {'project': 'project_value', 'membership': 'membership_value'}, 'networking': {'cluster_ipv4_cidr_blocks': ['cluster_ipv4_cidr_blocks_value1', 'cluster_ipv4_cidr_blocks_value2'], 'services_ipv4_cidr_blocks': ['services_ipv4_cidr_blocks_value1', 'services_ipv4_cidr_blocks_value2']}, 'authorization': {'admin_users': {'username': 'username_value'}}, 'default_max_pods_per_node': 2634, 'endpoint': 'endpoint_value', 'port': 453, 'cluster_ca_certificate': 'cluster_ca_certificate_value', 'maintenance_policy': {'window': {'recurring_window': {'window': {'start_time': {}, 'end_time': {}}, 'recurrence': 'recurrence_value'}}}, 'control_plane_version': 'control_plane_version_value', 'node_version': 'node_version_value', 'control_plane': {'remote': {}, 'local': {'node_location': 'node_location_value', 'node_count': 1070, 'machine_filter': 'machine_filter_value', 'shared_deployment_policy': 1}}, 'system_addons_config': {'ingress': {'disabled': True, 'ipv4_vip': 'ipv4_vip_value'}}, 'external_load_balancer_ipv4_address_pools': ['external_load_balancer_ipv4_address_pools_value1', 'external_load_balancer_ipv4_address_pools_value2'], 'control_plane_encryption': {'kms_key': 'kms_key_value', 'kms_key_active_version': 'kms_key_active_version_value', 'kms_key_state': 1, 'kms_status': {'code': 411, 'message': 'message_value', 'details': [{'type_url': 'type.googleapis.com/google.protobuf.Duration', 'value': b'\x08\x0c\x10\xdb\x07'}]}}, 'status': 1, 'maintenance_events': [{'uuid': 'uuid_value', 'target_version': 'target_version_value', 'operation': 'operation_value', 'type_': 1, 'schedule': 1, 'state': 1, 'create_time': {}, 'start_time': {}, 'end_time': {}, 'update_time': {}}], 'target_version': 'target_version_value', 'release_channel': 1, 'survivability_config': {'offline_reboot_ttl': {'seconds': 751, 'nanos': 543}}, 'external_load_balancer_ipv6_address_pools': ['external_load_balancer_ipv6_address_pools_value1', 'external_load_balancer_ipv6_address_pools_value2']} - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = service.CreateClusterRequest.meta.fields["cluster"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["cluster"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - {"field": field, "subfield": subfield, "is_repeated": is_repeated} - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["cluster"][field])): - del request_init["cluster"][field][i][subfield] - else: - del request_init["cluster"][field][subfield] - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # 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 - response = client.create_cluster(request) - - # Establish that the response is the type that we expect. - json_return_value = json_format.MessageToJson(return_value) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_cluster_rest_interceptors(null_interceptor): - transport = transports.EdgeContainerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EdgeContainerRestInterceptor(), - ) - client = EdgeContainerClient(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.EdgeContainerRestInterceptor, "post_create_cluster") as post, \ - mock.patch.object(transports.EdgeContainerRestInterceptor, "pre_create_cluster") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = service.CreateClusterRequest.pb(service.CreateClusterRequest()) - 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 - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = service.CreateClusterRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.create_cluster(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_cluster_rest_bad_request(request_type=service.UpdateClusterRequest): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'cluster': {'name': 'projects/sample1/locations/sample2/clusters/sample3'}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - client.update_cluster(request) - - -@pytest.mark.parametrize("request_type", [ - service.UpdateClusterRequest, - dict, -]) -def test_update_cluster_rest_call_success(request_type): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'cluster': {'name': 'projects/sample1/locations/sample2/clusters/sample3'}} - request_init["cluster"] = {'name': 'projects/sample1/locations/sample2/clusters/sample3', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'fleet': {'project': 'project_value', 'membership': 'membership_value'}, 'networking': {'cluster_ipv4_cidr_blocks': ['cluster_ipv4_cidr_blocks_value1', 'cluster_ipv4_cidr_blocks_value2'], 'services_ipv4_cidr_blocks': ['services_ipv4_cidr_blocks_value1', 'services_ipv4_cidr_blocks_value2']}, 'authorization': {'admin_users': {'username': 'username_value'}}, 'default_max_pods_per_node': 2634, 'endpoint': 'endpoint_value', 'port': 453, 'cluster_ca_certificate': 'cluster_ca_certificate_value', 'maintenance_policy': {'window': {'recurring_window': {'window': {'start_time': {}, 'end_time': {}}, 'recurrence': 'recurrence_value'}}}, 'control_plane_version': 'control_plane_version_value', 'node_version': 'node_version_value', 'control_plane': {'remote': {}, 'local': {'node_location': 'node_location_value', 'node_count': 1070, 'machine_filter': 'machine_filter_value', 'shared_deployment_policy': 1}}, 'system_addons_config': {'ingress': {'disabled': True, 'ipv4_vip': 'ipv4_vip_value'}}, 'external_load_balancer_ipv4_address_pools': ['external_load_balancer_ipv4_address_pools_value1', 'external_load_balancer_ipv4_address_pools_value2'], 'control_plane_encryption': {'kms_key': 'kms_key_value', 'kms_key_active_version': 'kms_key_active_version_value', 'kms_key_state': 1, 'kms_status': {'code': 411, 'message': 'message_value', 'details': [{'type_url': 'type.googleapis.com/google.protobuf.Duration', 'value': b'\x08\x0c\x10\xdb\x07'}]}}, 'status': 1, 'maintenance_events': [{'uuid': 'uuid_value', 'target_version': 'target_version_value', 'operation': 'operation_value', 'type_': 1, 'schedule': 1, 'state': 1, 'create_time': {}, 'start_time': {}, 'end_time': {}, 'update_time': {}}], 'target_version': 'target_version_value', 'release_channel': 1, 'survivability_config': {'offline_reboot_ttl': {'seconds': 751, 'nanos': 543}}, 'external_load_balancer_ipv6_address_pools': ['external_load_balancer_ipv6_address_pools_value1', 'external_load_balancer_ipv6_address_pools_value2']} - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = service.UpdateClusterRequest.meta.fields["cluster"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["cluster"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - {"field": field, "subfield": subfield, "is_repeated": is_repeated} - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["cluster"][field])): - del request_init["cluster"][field][i][subfield] - else: - del request_init["cluster"][field][subfield] - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # 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 - response = client.update_cluster(request) - - # Establish that the response is the type that we expect. - json_return_value = json_format.MessageToJson(return_value) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_cluster_rest_interceptors(null_interceptor): - transport = transports.EdgeContainerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EdgeContainerRestInterceptor(), - ) - client = EdgeContainerClient(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.EdgeContainerRestInterceptor, "post_update_cluster") as post, \ - mock.patch.object(transports.EdgeContainerRestInterceptor, "pre_update_cluster") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = service.UpdateClusterRequest.pb(service.UpdateClusterRequest()) - 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 - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = service.UpdateClusterRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.update_cluster(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_upgrade_cluster_rest_bad_request(request_type=service.UpgradeClusterRequest): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - client.upgrade_cluster(request) - - -@pytest.mark.parametrize("request_type", [ - service.UpgradeClusterRequest, - dict, -]) -def test_upgrade_cluster_rest_call_success(request_type): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = 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 - response = client.upgrade_cluster(request) - - # Establish that the response is the type that we expect. - json_return_value = json_format.MessageToJson(return_value) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_upgrade_cluster_rest_interceptors(null_interceptor): - transport = transports.EdgeContainerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EdgeContainerRestInterceptor(), - ) - client = EdgeContainerClient(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.EdgeContainerRestInterceptor, "post_upgrade_cluster") as post, \ - mock.patch.object(transports.EdgeContainerRestInterceptor, "pre_upgrade_cluster") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = service.UpgradeClusterRequest.pb(service.UpgradeClusterRequest()) - 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 - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = service.UpgradeClusterRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.upgrade_cluster(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_cluster_rest_bad_request(request_type=service.DeleteClusterRequest): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - client.delete_cluster(request) - - -@pytest.mark.parametrize("request_type", [ - service.DeleteClusterRequest, - dict, -]) -def test_delete_cluster_rest_call_success(request_type): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = 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 - response = client.delete_cluster(request) - - # Establish that the response is the type that we expect. - json_return_value = json_format.MessageToJson(return_value) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_cluster_rest_interceptors(null_interceptor): - transport = transports.EdgeContainerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EdgeContainerRestInterceptor(), - ) - client = EdgeContainerClient(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.EdgeContainerRestInterceptor, "post_delete_cluster") as post, \ - mock.patch.object(transports.EdgeContainerRestInterceptor, "pre_delete_cluster") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = service.DeleteClusterRequest.pb(service.DeleteClusterRequest()) - 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 - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = service.DeleteClusterRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.delete_cluster(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_generate_access_token_rest_bad_request(request_type=service.GenerateAccessTokenRequest): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'cluster': 'projects/sample1/locations/sample2/clusters/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - client.generate_access_token(request) - - -@pytest.mark.parametrize("request_type", [ - service.GenerateAccessTokenRequest, - dict, -]) -def test_generate_access_token_rest_call_success(request_type): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'cluster': 'projects/sample1/locations/sample2/clusters/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = service.GenerateAccessTokenResponse( - access_token='access_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = service.GenerateAccessTokenResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.generate_access_token(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, service.GenerateAccessTokenResponse) - assert response.access_token == 'access_token_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_generate_access_token_rest_interceptors(null_interceptor): - transport = transports.EdgeContainerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EdgeContainerRestInterceptor(), - ) - client = EdgeContainerClient(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.EdgeContainerRestInterceptor, "post_generate_access_token") as post, \ - mock.patch.object(transports.EdgeContainerRestInterceptor, "pre_generate_access_token") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = service.GenerateAccessTokenRequest.pb(service.GenerateAccessTokenRequest()) - 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 - return_value = service.GenerateAccessTokenResponse.to_json(service.GenerateAccessTokenResponse()) - req.return_value.content = return_value - - request = service.GenerateAccessTokenRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = service.GenerateAccessTokenResponse() - - client.generate_access_token(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_generate_offline_credential_rest_bad_request(request_type=service.GenerateOfflineCredentialRequest): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'cluster': 'projects/sample1/locations/sample2/clusters/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - client.generate_offline_credential(request) - - -@pytest.mark.parametrize("request_type", [ - service.GenerateOfflineCredentialRequest, - dict, -]) -def test_generate_offline_credential_rest_call_success(request_type): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'cluster': 'projects/sample1/locations/sample2/clusters/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = service.GenerateOfflineCredentialResponse( - client_certificate='client_certificate_value', - client_key='client_key_value', - user_id='user_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 = service.GenerateOfflineCredentialResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.generate_offline_credential(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, service.GenerateOfflineCredentialResponse) - assert response.client_certificate == 'client_certificate_value' - assert response.client_key == 'client_key_value' - assert response.user_id == 'user_id_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_generate_offline_credential_rest_interceptors(null_interceptor): - transport = transports.EdgeContainerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EdgeContainerRestInterceptor(), - ) - client = EdgeContainerClient(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.EdgeContainerRestInterceptor, "post_generate_offline_credential") as post, \ - mock.patch.object(transports.EdgeContainerRestInterceptor, "pre_generate_offline_credential") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = service.GenerateOfflineCredentialRequest.pb(service.GenerateOfflineCredentialRequest()) - 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 - return_value = service.GenerateOfflineCredentialResponse.to_json(service.GenerateOfflineCredentialResponse()) - req.return_value.content = return_value - - request = service.GenerateOfflineCredentialRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = service.GenerateOfflineCredentialResponse() - - client.generate_offline_credential(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_node_pools_rest_bad_request(request_type=service.ListNodePoolsRequest): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - client.list_node_pools(request) - - -@pytest.mark.parametrize("request_type", [ - service.ListNodePoolsRequest, - dict, -]) -def test_list_node_pools_rest_call_success(request_type): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = service.ListNodePoolsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = service.ListNodePoolsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_node_pools(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListNodePoolsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_node_pools_rest_interceptors(null_interceptor): - transport = transports.EdgeContainerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EdgeContainerRestInterceptor(), - ) - client = EdgeContainerClient(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.EdgeContainerRestInterceptor, "post_list_node_pools") as post, \ - mock.patch.object(transports.EdgeContainerRestInterceptor, "pre_list_node_pools") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = service.ListNodePoolsRequest.pb(service.ListNodePoolsRequest()) - 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 - return_value = service.ListNodePoolsResponse.to_json(service.ListNodePoolsResponse()) - req.return_value.content = return_value - - request = service.ListNodePoolsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = service.ListNodePoolsResponse() - - client.list_node_pools(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_node_pool_rest_bad_request(request_type=service.GetNodePoolRequest): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3/nodePools/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - client.get_node_pool(request) - - -@pytest.mark.parametrize("request_type", [ - service.GetNodePoolRequest, - dict, -]) -def test_get_node_pool_rest_call_success(request_type): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3/nodePools/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = resources.NodePool( - name='name_value', - node_location='node_location_value', - node_count=1070, - machine_filter='machine_filter_value', - node_version='node_version_value', - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = resources.NodePool.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_node_pool(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.NodePool) - assert response.name == 'name_value' - assert response.node_location == 'node_location_value' - assert response.node_count == 1070 - assert response.machine_filter == 'machine_filter_value' - assert response.node_version == 'node_version_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_node_pool_rest_interceptors(null_interceptor): - transport = transports.EdgeContainerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EdgeContainerRestInterceptor(), - ) - client = EdgeContainerClient(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.EdgeContainerRestInterceptor, "post_get_node_pool") as post, \ - mock.patch.object(transports.EdgeContainerRestInterceptor, "pre_get_node_pool") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = service.GetNodePoolRequest.pb(service.GetNodePoolRequest()) - 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 - return_value = resources.NodePool.to_json(resources.NodePool()) - req.return_value.content = return_value - - request = service.GetNodePoolRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = resources.NodePool() - - client.get_node_pool(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_node_pool_rest_bad_request(request_type=service.CreateNodePoolRequest): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - client.create_node_pool(request) - - -@pytest.mark.parametrize("request_type", [ - service.CreateNodePoolRequest, - dict, -]) -def test_create_node_pool_rest_call_success(request_type): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/clusters/sample3'} - request_init["node_pool"] = {'name': 'name_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'node_location': 'node_location_value', 'node_count': 1070, 'machine_filter': 'machine_filter_value', 'local_disk_encryption': {'kms_key': 'kms_key_value', 'kms_key_active_version': 'kms_key_active_version_value', 'kms_key_state': 1, 'kms_status': {'code': 411, 'message': 'message_value', 'details': [{'type_url': 'type.googleapis.com/google.protobuf.Duration', 'value': b'\x08\x0c\x10\xdb\x07'}]}}, 'node_version': 'node_version_value', 'node_config': {'labels': {}}} - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = service.CreateNodePoolRequest.meta.fields["node_pool"] - - 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["node_pool"].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["node_pool"][field])): - del request_init["node_pool"][field][i][subfield] - else: - del request_init["node_pool"][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 - response = client.create_node_pool(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_node_pool_rest_interceptors(null_interceptor): - transport = transports.EdgeContainerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EdgeContainerRestInterceptor(), - ) - client = EdgeContainerClient(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.EdgeContainerRestInterceptor, "post_create_node_pool") as post, \ - mock.patch.object(transports.EdgeContainerRestInterceptor, "pre_create_node_pool") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = service.CreateNodePoolRequest.pb(service.CreateNodePoolRequest()) - 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 - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = service.CreateNodePoolRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.create_node_pool(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_node_pool_rest_bad_request(request_type=service.UpdateNodePoolRequest): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'node_pool': {'name': 'projects/sample1/locations/sample2/clusters/sample3/nodePools/sample4'}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - client.update_node_pool(request) - - -@pytest.mark.parametrize("request_type", [ - service.UpdateNodePoolRequest, - dict, -]) -def test_update_node_pool_rest_call_success(request_type): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'node_pool': {'name': 'projects/sample1/locations/sample2/clusters/sample3/nodePools/sample4'}} - request_init["node_pool"] = {'name': 'projects/sample1/locations/sample2/clusters/sample3/nodePools/sample4', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'node_location': 'node_location_value', 'node_count': 1070, 'machine_filter': 'machine_filter_value', 'local_disk_encryption': {'kms_key': 'kms_key_value', 'kms_key_active_version': 'kms_key_active_version_value', 'kms_key_state': 1, 'kms_status': {'code': 411, 'message': 'message_value', 'details': [{'type_url': 'type.googleapis.com/google.protobuf.Duration', 'value': b'\x08\x0c\x10\xdb\x07'}]}}, 'node_version': 'node_version_value', 'node_config': {'labels': {}}} - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = service.UpdateNodePoolRequest.meta.fields["node_pool"] - - 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["node_pool"].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["node_pool"][field])): - del request_init["node_pool"][field][i][subfield] - else: - del request_init["node_pool"][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 - response = client.update_node_pool(request) - - # Establish that the response is the type that we expect. - json_return_value = json_format.MessageToJson(return_value) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_node_pool_rest_interceptors(null_interceptor): - transport = transports.EdgeContainerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EdgeContainerRestInterceptor(), - ) - client = EdgeContainerClient(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.EdgeContainerRestInterceptor, "post_update_node_pool") as post, \ - mock.patch.object(transports.EdgeContainerRestInterceptor, "pre_update_node_pool") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = service.UpdateNodePoolRequest.pb(service.UpdateNodePoolRequest()) - 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 - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = service.UpdateNodePoolRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.update_node_pool(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_node_pool_rest_bad_request(request_type=service.DeleteNodePoolRequest): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3/nodePools/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - client.delete_node_pool(request) - - -@pytest.mark.parametrize("request_type", [ - service.DeleteNodePoolRequest, - dict, -]) -def test_delete_node_pool_rest_call_success(request_type): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/clusters/sample3/nodePools/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.delete_node_pool(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_node_pool_rest_interceptors(null_interceptor): - transport = transports.EdgeContainerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EdgeContainerRestInterceptor(), - ) - client = EdgeContainerClient(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.EdgeContainerRestInterceptor, "post_delete_node_pool") as post, \ - mock.patch.object(transports.EdgeContainerRestInterceptor, "pre_delete_node_pool") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = service.DeleteNodePoolRequest.pb(service.DeleteNodePoolRequest()) - 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 - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = service.DeleteNodePoolRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.delete_node_pool(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_machines_rest_bad_request(request_type=service.ListMachinesRequest): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - client.list_machines(request) - - -@pytest.mark.parametrize("request_type", [ - service.ListMachinesRequest, - dict, -]) -def test_list_machines_rest_call_success(request_type): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = service.ListMachinesResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = service.ListMachinesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_machines(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListMachinesPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_machines_rest_interceptors(null_interceptor): - transport = transports.EdgeContainerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EdgeContainerRestInterceptor(), - ) - client = EdgeContainerClient(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.EdgeContainerRestInterceptor, "post_list_machines") as post, \ - mock.patch.object(transports.EdgeContainerRestInterceptor, "pre_list_machines") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = service.ListMachinesRequest.pb(service.ListMachinesRequest()) - 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 - return_value = service.ListMachinesResponse.to_json(service.ListMachinesResponse()) - req.return_value.content = return_value - - request = service.ListMachinesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = service.ListMachinesResponse() - - client.list_machines(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_machine_rest_bad_request(request_type=service.GetMachineRequest): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/machines/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - client.get_machine(request) - - -@pytest.mark.parametrize("request_type", [ - service.GetMachineRequest, - dict, -]) -def test_get_machine_rest_call_success(request_type): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/machines/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = resources.Machine( - name='name_value', - hosted_node='hosted_node_value', - zone='zone_value', - version='version_value', - disabled=True, - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = resources.Machine.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_machine(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.Machine) - assert response.name == 'name_value' - assert response.hosted_node == 'hosted_node_value' - assert response.zone == 'zone_value' - assert response.version == 'version_value' - assert response.disabled is True - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_machine_rest_interceptors(null_interceptor): - transport = transports.EdgeContainerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EdgeContainerRestInterceptor(), - ) - client = EdgeContainerClient(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.EdgeContainerRestInterceptor, "post_get_machine") as post, \ - mock.patch.object(transports.EdgeContainerRestInterceptor, "pre_get_machine") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = service.GetMachineRequest.pb(service.GetMachineRequest()) - 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 - return_value = resources.Machine.to_json(resources.Machine()) - req.return_value.content = return_value - - request = service.GetMachineRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = resources.Machine() - - client.get_machine(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_vpn_connections_rest_bad_request(request_type=service.ListVpnConnectionsRequest): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - client.list_vpn_connections(request) - - -@pytest.mark.parametrize("request_type", [ - service.ListVpnConnectionsRequest, - dict, -]) -def test_list_vpn_connections_rest_call_success(request_type): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = service.ListVpnConnectionsResponse( - next_page_token='next_page_token_value', - unreachable=['unreachable_value'], - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = service.ListVpnConnectionsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_vpn_connections(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListVpnConnectionsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.unreachable == ['unreachable_value'] - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_vpn_connections_rest_interceptors(null_interceptor): - transport = transports.EdgeContainerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EdgeContainerRestInterceptor(), - ) - client = EdgeContainerClient(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.EdgeContainerRestInterceptor, "post_list_vpn_connections") as post, \ - mock.patch.object(transports.EdgeContainerRestInterceptor, "pre_list_vpn_connections") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = service.ListVpnConnectionsRequest.pb(service.ListVpnConnectionsRequest()) - 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 - return_value = service.ListVpnConnectionsResponse.to_json(service.ListVpnConnectionsResponse()) - req.return_value.content = return_value - - request = service.ListVpnConnectionsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = service.ListVpnConnectionsResponse() - - client.list_vpn_connections(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_vpn_connection_rest_bad_request(request_type=service.GetVpnConnectionRequest): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/vpnConnections/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - client.get_vpn_connection(request) - - -@pytest.mark.parametrize("request_type", [ - service.GetVpnConnectionRequest, - dict, -]) -def test_get_vpn_connection_rest_call_success(request_type): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/vpnConnections/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = resources.VpnConnection( - name='name_value', - nat_gateway_ip='nat_gateway_ip_value', - bgp_routing_mode=resources.VpnConnection.BgpRoutingMode.REGIONAL, - cluster='cluster_value', - vpc='vpc_value', - enable_high_availability=True, - router='router_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.VpnConnection.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_vpn_connection(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.VpnConnection) - assert response.name == 'name_value' - assert response.nat_gateway_ip == 'nat_gateway_ip_value' - assert response.bgp_routing_mode == resources.VpnConnection.BgpRoutingMode.REGIONAL - assert response.cluster == 'cluster_value' - assert response.vpc == 'vpc_value' - assert response.enable_high_availability is True - assert response.router == 'router_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_vpn_connection_rest_interceptors(null_interceptor): - transport = transports.EdgeContainerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EdgeContainerRestInterceptor(), - ) - client = EdgeContainerClient(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.EdgeContainerRestInterceptor, "post_get_vpn_connection") as post, \ - mock.patch.object(transports.EdgeContainerRestInterceptor, "pre_get_vpn_connection") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = service.GetVpnConnectionRequest.pb(service.GetVpnConnectionRequest()) - 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 - return_value = resources.VpnConnection.to_json(resources.VpnConnection()) - req.return_value.content = return_value - - request = service.GetVpnConnectionRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = resources.VpnConnection() - - client.get_vpn_connection(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_vpn_connection_rest_bad_request(request_type=service.CreateVpnConnectionRequest): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - client.create_vpn_connection(request) - - -@pytest.mark.parametrize("request_type", [ - service.CreateVpnConnectionRequest, - dict, -]) -def test_create_vpn_connection_rest_call_success(request_type): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request_init["vpn_connection"] = {'name': 'name_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'labels': {}, 'nat_gateway_ip': 'nat_gateway_ip_value', 'bgp_routing_mode': 1, 'cluster': 'cluster_value', 'vpc': 'vpc_value', 'vpc_project': {'project_id': 'project_id_value', 'service_account': 'service_account_value'}, 'enable_high_availability': True, 'router': 'router_value', 'details': {'state': 1, 'error': 'error_value', 'cloud_router': {'name': 'name_value'}, 'cloud_vpns': [{'gateway': 'gateway_value'}]}} - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = service.CreateVpnConnectionRequest.meta.fields["vpn_connection"] - - 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["vpn_connection"].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["vpn_connection"][field])): - del request_init["vpn_connection"][field][i][subfield] - else: - del request_init["vpn_connection"][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 - response = client.create_vpn_connection(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_vpn_connection_rest_interceptors(null_interceptor): - transport = transports.EdgeContainerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EdgeContainerRestInterceptor(), - ) - client = EdgeContainerClient(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.EdgeContainerRestInterceptor, "post_create_vpn_connection") as post, \ - mock.patch.object(transports.EdgeContainerRestInterceptor, "pre_create_vpn_connection") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = service.CreateVpnConnectionRequest.pb(service.CreateVpnConnectionRequest()) - 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 - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = service.CreateVpnConnectionRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.create_vpn_connection(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_vpn_connection_rest_bad_request(request_type=service.DeleteVpnConnectionRequest): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/vpnConnections/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - client.delete_vpn_connection(request) - - -@pytest.mark.parametrize("request_type", [ - service.DeleteVpnConnectionRequest, - dict, -]) -def test_delete_vpn_connection_rest_call_success(request_type): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/vpnConnections/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.delete_vpn_connection(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_vpn_connection_rest_interceptors(null_interceptor): - transport = transports.EdgeContainerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EdgeContainerRestInterceptor(), - ) - client = EdgeContainerClient(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.EdgeContainerRestInterceptor, "post_delete_vpn_connection") as post, \ - mock.patch.object(transports.EdgeContainerRestInterceptor, "pre_delete_vpn_connection") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = service.DeleteVpnConnectionRequest.pb(service.DeleteVpnConnectionRequest()) - 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 - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = service.DeleteVpnConnectionRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.delete_vpn_connection(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_server_config_rest_bad_request(request_type=service.GetServerConfigRequest): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - client.get_server_config(request) - - -@pytest.mark.parametrize("request_type", [ - service.GetServerConfigRequest, - dict, -]) -def test_get_server_config_rest_call_success(request_type): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = resources.ServerConfig( - default_version='default_version_value', - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = resources.ServerConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_server_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.ServerConfig) - assert response.default_version == 'default_version_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_server_config_rest_interceptors(null_interceptor): - transport = transports.EdgeContainerRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EdgeContainerRestInterceptor(), - ) - client = EdgeContainerClient(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.EdgeContainerRestInterceptor, "post_get_server_config") as post, \ - mock.patch.object(transports.EdgeContainerRestInterceptor, "pre_get_server_config") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = service.GetServerConfigRequest.pb(service.GetServerConfigRequest()) - 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 - return_value = resources.ServerConfig.to_json(resources.ServerConfig()) - req.return_value.content = return_value - - request = service.GetServerConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = resources.ServerConfig() - - client.get_server_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_location_rest_bad_request(request_type=locations_pb2.GetLocationRequest): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_location(request) - - -@pytest.mark.parametrize("request_type", [ - locations_pb2.GetLocationRequest, - dict, -]) -def test_get_location_rest(request_type): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'name': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.Location() - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - - req.return_value = response_value - - response = client.get_location(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - - -def test_list_locations_rest_bad_request(request_type=locations_pb2.ListLocationsRequest): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_locations(request) - - -@pytest.mark.parametrize("request_type", [ - locations_pb2.ListLocationsRequest, - dict, -]) -def test_list_locations_rest(request_type): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'name': 'projects/sample1'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.ListLocationsResponse() - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - - req.return_value = response_value - - response = client.list_locations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - - -def test_cancel_operation_rest_bad_request(request_type=operations_pb2.CancelOperationRequest): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.cancel_operation(request) - - -@pytest.mark.parametrize("request_type", [ - operations_pb2.CancelOperationRequest, - dict, -]) -def test_cancel_operation_rest(request_type): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = '{}' - response_value.content = json_return_value.encode('UTF-8') - - req.return_value = response_value - - response = client.cancel_operation(request) - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_operation_rest_bad_request(request_type=operations_pb2.DeleteOperationRequest): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_operation(request) - - -@pytest.mark.parametrize("request_type", [ - operations_pb2.DeleteOperationRequest, - dict, -]) -def test_delete_operation_rest(request_type): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = '{}' - response_value.content = json_return_value.encode('UTF-8') - - req.return_value = response_value - - response = client.delete_operation(request) - - # Establish that the response is the type that we expect. - assert response is None - - -def test_get_operation_rest_bad_request(request_type=operations_pb2.GetOperationRequest): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_operation(request) - - -@pytest.mark.parametrize("request_type", [ - operations_pb2.GetOperationRequest, - dict, -]) -def test_get_operation_rest(request_type): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - - -def test_list_operations_rest_bad_request(request_type=operations_pb2.ListOperationsRequest): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_operations(request) - - -@pytest.mark.parametrize("request_type", [ - operations_pb2.ListOperationsRequest, - dict, -]) -def test_list_operations_rest(request_type): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'name': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - - req.return_value = response_value - - 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 = EdgeContainerClient( - 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_clusters_empty_call_rest(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_clusters), - '__call__') as call: - client.list_clusters(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.ListClustersRequest() - - assert args[0] == request_msg - - -# This 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_cluster_empty_call_rest(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_cluster), - '__call__') as call: - client.get_cluster(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.GetClusterRequest() - - assert args[0] == request_msg - - -# This 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_cluster_empty_call_rest(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_cluster), - '__call__') as call: - client.create_cluster(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.CreateClusterRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_update_cluster_empty_call_rest(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_cluster), - '__call__') as call: - client.update_cluster(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.UpdateClusterRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_upgrade_cluster_empty_call_rest(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.upgrade_cluster), - '__call__') as call: - client.upgrade_cluster(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.UpgradeClusterRequest() - - assert args[0] == request_msg - - -# This 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_cluster_empty_call_rest(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_cluster), - '__call__') as call: - client.delete_cluster(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.DeleteClusterRequest() - - assert args[0] == request_msg - - -# This 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_access_token_empty_call_rest(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.generate_access_token), - '__call__') as call: - client.generate_access_token(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.GenerateAccessTokenRequest() - - assert args[0] == request_msg - - -# This 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_offline_credential_empty_call_rest(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.generate_offline_credential), - '__call__') as call: - client.generate_offline_credential(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.GenerateOfflineCredentialRequest() - - assert args[0] == request_msg - - -# This 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_node_pools_empty_call_rest(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_node_pools), - '__call__') as call: - client.list_node_pools(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.ListNodePoolsRequest() - - assert args[0] == request_msg - - -# This 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_node_pool_empty_call_rest(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_node_pool), - '__call__') as call: - client.get_node_pool(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.GetNodePoolRequest() - - assert args[0] == request_msg - - -# This 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_node_pool_empty_call_rest(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_node_pool), - '__call__') as call: - client.create_node_pool(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.CreateNodePoolRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_update_node_pool_empty_call_rest(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_node_pool), - '__call__') as call: - client.update_node_pool(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.UpdateNodePoolRequest() - - assert args[0] == request_msg - - -# This 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_node_pool_empty_call_rest(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_node_pool), - '__call__') as call: - client.delete_node_pool(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.DeleteNodePoolRequest() - - assert args[0] == request_msg - - -# This 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_machines_empty_call_rest(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_machines), - '__call__') as call: - client.list_machines(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.ListMachinesRequest() - - assert args[0] == request_msg - - -# This 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_machine_empty_call_rest(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_machine), - '__call__') as call: - client.get_machine(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.GetMachineRequest() - - assert args[0] == request_msg - - -# This 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_vpn_connections_empty_call_rest(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_vpn_connections), - '__call__') as call: - client.list_vpn_connections(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.ListVpnConnectionsRequest() - - assert args[0] == request_msg - - -# This 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_vpn_connection_empty_call_rest(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_vpn_connection), - '__call__') as call: - client.get_vpn_connection(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.GetVpnConnectionRequest() - - assert args[0] == request_msg - - -# This 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_vpn_connection_empty_call_rest(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_vpn_connection), - '__call__') as call: - client.create_vpn_connection(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.CreateVpnConnectionRequest() - - assert args[0] == request_msg - - -# This 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_vpn_connection_empty_call_rest(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_vpn_connection), - '__call__') as call: - client.delete_vpn_connection(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.DeleteVpnConnectionRequest() - - assert args[0] == request_msg - - -# This 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_server_config_empty_call_rest(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_server_config), - '__call__') as call: - client.get_server_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.GetServerConfigRequest() - - assert args[0] == request_msg - - -def test_edge_container_rest_lro_client(): - client = EdgeContainerClient( - 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 = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.EdgeContainerGrpcTransport, - ) - -def test_edge_container_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.EdgeContainerTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_edge_container_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.edgecontainer_v1.services.edge_container.transports.EdgeContainerTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.EdgeContainerTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'list_clusters', - 'get_cluster', - 'create_cluster', - 'update_cluster', - 'upgrade_cluster', - 'delete_cluster', - 'generate_access_token', - 'generate_offline_credential', - 'list_node_pools', - 'get_node_pool', - 'create_node_pool', - 'update_node_pool', - 'delete_node_pool', - 'list_machines', - 'get_machine', - 'list_vpn_connections', - 'get_vpn_connection', - 'create_vpn_connection', - 'delete_vpn_connection', - 'get_server_config', - 'get_location', - 'list_locations', - 'get_operation', - 'cancel_operation', - 'delete_operation', - 'list_operations', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - with pytest.raises(NotImplementedError): - transport.close() - - # Additionally, the LRO client (a property) should - # also raise NotImplementedError - with pytest.raises(NotImplementedError): - transport.operations_client - - # Catch all for all remaining methods and properties - remainder = [ - 'kind', - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() - - -def test_edge_container_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.edgecontainer_v1.services.edge_container.transports.EdgeContainerTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.EdgeContainerTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with("credentials.json", - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id="octopus", - ) - - -def test_edge_container_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.edgecontainer_v1.services.edge_container.transports.EdgeContainerTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.EdgeContainerTransport() - adc.assert_called_once() - - -def test_edge_container_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) - EdgeContainerClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.EdgeContainerGrpcTransport, - transports.EdgeContainerGrpcAsyncIOTransport, - ], -) -def test_edge_container_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.EdgeContainerGrpcTransport, - transports.EdgeContainerGrpcAsyncIOTransport, - transports.EdgeContainerRestTransport, - ], -) -def test_edge_container_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.EdgeContainerGrpcTransport, grpc_helpers), - (transports.EdgeContainerGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_edge_container_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( - "edgecontainer.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - scopes=["1", "2"], - default_host="edgecontainer.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.EdgeContainerGrpcTransport, transports.EdgeContainerGrpcAsyncIOTransport]) -def test_edge_container_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_edge_container_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.EdgeContainerRestTransport ( - 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_edge_container_host_no_port(transport_name): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='edgecontainer.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'edgecontainer.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://edgecontainer.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_edge_container_host_with_port(transport_name): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='edgecontainer.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'edgecontainer.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://edgecontainer.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_edge_container_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = EdgeContainerClient( - credentials=creds1, - transport=transport_name, - ) - client2 = EdgeContainerClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.list_clusters._session - session2 = client2.transport.list_clusters._session - assert session1 != session2 - session1 = client1.transport.get_cluster._session - session2 = client2.transport.get_cluster._session - assert session1 != session2 - session1 = client1.transport.create_cluster._session - session2 = client2.transport.create_cluster._session - assert session1 != session2 - session1 = client1.transport.update_cluster._session - session2 = client2.transport.update_cluster._session - assert session1 != session2 - session1 = client1.transport.upgrade_cluster._session - session2 = client2.transport.upgrade_cluster._session - assert session1 != session2 - session1 = client1.transport.delete_cluster._session - session2 = client2.transport.delete_cluster._session - assert session1 != session2 - session1 = client1.transport.generate_access_token._session - session2 = client2.transport.generate_access_token._session - assert session1 != session2 - session1 = client1.transport.generate_offline_credential._session - session2 = client2.transport.generate_offline_credential._session - assert session1 != session2 - session1 = client1.transport.list_node_pools._session - session2 = client2.transport.list_node_pools._session - assert session1 != session2 - session1 = client1.transport.get_node_pool._session - session2 = client2.transport.get_node_pool._session - assert session1 != session2 - session1 = client1.transport.create_node_pool._session - session2 = client2.transport.create_node_pool._session - assert session1 != session2 - session1 = client1.transport.update_node_pool._session - session2 = client2.transport.update_node_pool._session - assert session1 != session2 - session1 = client1.transport.delete_node_pool._session - session2 = client2.transport.delete_node_pool._session - assert session1 != session2 - session1 = client1.transport.list_machines._session - session2 = client2.transport.list_machines._session - assert session1 != session2 - session1 = client1.transport.get_machine._session - session2 = client2.transport.get_machine._session - assert session1 != session2 - session1 = client1.transport.list_vpn_connections._session - session2 = client2.transport.list_vpn_connections._session - assert session1 != session2 - session1 = client1.transport.get_vpn_connection._session - session2 = client2.transport.get_vpn_connection._session - assert session1 != session2 - session1 = client1.transport.create_vpn_connection._session - session2 = client2.transport.create_vpn_connection._session - assert session1 != session2 - session1 = client1.transport.delete_vpn_connection._session - session2 = client2.transport.delete_vpn_connection._session - assert session1 != session2 - session1 = client1.transport.get_server_config._session - session2 = client2.transport.get_server_config._session - assert session1 != session2 -def test_edge_container_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.EdgeContainerGrpcTransport( - 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_edge_container_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.EdgeContainerGrpcAsyncIOTransport( - 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.EdgeContainerGrpcTransport, transports.EdgeContainerGrpcAsyncIOTransport]) -def test_edge_container_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.EdgeContainerGrpcTransport, transports.EdgeContainerGrpcAsyncIOTransport]) -def test_edge_container_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_edge_container_grpc_lro_client(): - client = EdgeContainerClient( - 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_edge_container_grpc_lro_async_client(): - client = EdgeContainerAsyncClient( - 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_cluster_path(): - project = "squid" - location = "clam" - cluster = "whelk" - expected = "projects/{project}/locations/{location}/clusters/{cluster}".format(project=project, location=location, cluster=cluster, ) - actual = EdgeContainerClient.cluster_path(project, location, cluster) - assert expected == actual - - -def test_parse_cluster_path(): - expected = { - "project": "octopus", - "location": "oyster", - "cluster": "nudibranch", - } - path = EdgeContainerClient.cluster_path(**expected) - - # Check that the path construction is reversible. - actual = EdgeContainerClient.parse_cluster_path(path) - assert expected == actual - -def test_crypto_key_path(): - project = "cuttlefish" - location = "mussel" - key_ring = "winkle" - crypto_key = "nautilus" - expected = "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}".format(project=project, location=location, key_ring=key_ring, crypto_key=crypto_key, ) - actual = EdgeContainerClient.crypto_key_path(project, location, key_ring, crypto_key) - assert expected == actual - - -def test_parse_crypto_key_path(): - expected = { - "project": "scallop", - "location": "abalone", - "key_ring": "squid", - "crypto_key": "clam", - } - path = EdgeContainerClient.crypto_key_path(**expected) - - # Check that the path construction is reversible. - actual = EdgeContainerClient.parse_crypto_key_path(path) - assert expected == actual - -def test_crypto_key_version_path(): - project = "whelk" - location = "octopus" - key_ring = "oyster" - crypto_key = "nudibranch" - crypto_key_version = "cuttlefish" - expected = "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}/cryptoKeyVersions/{crypto_key_version}".format(project=project, location=location, key_ring=key_ring, crypto_key=crypto_key, crypto_key_version=crypto_key_version, ) - actual = EdgeContainerClient.crypto_key_version_path(project, location, key_ring, crypto_key, crypto_key_version) - assert expected == actual - - -def test_parse_crypto_key_version_path(): - expected = { - "project": "mussel", - "location": "winkle", - "key_ring": "nautilus", - "crypto_key": "scallop", - "crypto_key_version": "abalone", - } - path = EdgeContainerClient.crypto_key_version_path(**expected) - - # Check that the path construction is reversible. - actual = EdgeContainerClient.parse_crypto_key_version_path(path) - assert expected == actual - -def test_machine_path(): - project = "squid" - location = "clam" - machine = "whelk" - expected = "projects/{project}/locations/{location}/machines/{machine}".format(project=project, location=location, machine=machine, ) - actual = EdgeContainerClient.machine_path(project, location, machine) - assert expected == actual - - -def test_parse_machine_path(): - expected = { - "project": "octopus", - "location": "oyster", - "machine": "nudibranch", - } - path = EdgeContainerClient.machine_path(**expected) - - # Check that the path construction is reversible. - actual = EdgeContainerClient.parse_machine_path(path) - assert expected == actual - -def test_node_pool_path(): - project = "cuttlefish" - location = "mussel" - cluster = "winkle" - node_pool = "nautilus" - expected = "projects/{project}/locations/{location}/clusters/{cluster}/nodePools/{node_pool}".format(project=project, location=location, cluster=cluster, node_pool=node_pool, ) - actual = EdgeContainerClient.node_pool_path(project, location, cluster, node_pool) - assert expected == actual - - -def test_parse_node_pool_path(): - expected = { - "project": "scallop", - "location": "abalone", - "cluster": "squid", - "node_pool": "clam", - } - path = EdgeContainerClient.node_pool_path(**expected) - - # Check that the path construction is reversible. - actual = EdgeContainerClient.parse_node_pool_path(path) - assert expected == actual - -def test_vpn_connection_path(): - project = "whelk" - location = "octopus" - vpn_connection = "oyster" - expected = "projects/{project}/locations/{location}/vpnConnections/{vpn_connection}".format(project=project, location=location, vpn_connection=vpn_connection, ) - actual = EdgeContainerClient.vpn_connection_path(project, location, vpn_connection) - assert expected == actual - - -def test_parse_vpn_connection_path(): - expected = { - "project": "nudibranch", - "location": "cuttlefish", - "vpn_connection": "mussel", - } - path = EdgeContainerClient.vpn_connection_path(**expected) - - # Check that the path construction is reversible. - actual = EdgeContainerClient.parse_vpn_connection_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "winkle" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = EdgeContainerClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "nautilus", - } - path = EdgeContainerClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = EdgeContainerClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "scallop" - expected = "folders/{folder}".format(folder=folder, ) - actual = EdgeContainerClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "abalone", - } - path = EdgeContainerClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = EdgeContainerClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "squid" - expected = "organizations/{organization}".format(organization=organization, ) - actual = EdgeContainerClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "clam", - } - path = EdgeContainerClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = EdgeContainerClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "whelk" - expected = "projects/{project}".format(project=project, ) - actual = EdgeContainerClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "octopus", - } - path = EdgeContainerClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = EdgeContainerClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "oyster" - location = "nudibranch" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = EdgeContainerClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "cuttlefish", - "location": "mussel", - } - path = EdgeContainerClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = EdgeContainerClient.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.EdgeContainerTransport, '_prep_wrapped_messages') as prep: - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.EdgeContainerTransport, '_prep_wrapped_messages') as prep: - transport_class = EdgeContainerClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - -def test_delete_operation(transport: str = "grpc"): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.DeleteOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None -@pytest.mark.asyncio -async def test_delete_operation_async(transport: str = "grpc_asyncio"): - client = EdgeContainerAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.DeleteOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.delete_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None - -def test_delete_operation_field_headers(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = operations_pb2.DeleteOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: - call.return_value = None - - client.delete_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_delete_operation_field_headers_async(): - client = EdgeContainerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = operations_pb2.DeleteOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - await client.delete_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] - -def test_delete_operation_from_dict(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - - response = client.delete_operation( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_delete_operation_from_dict_async(): - client = EdgeContainerAsyncClient( - credentials=async_anonymous_credentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.delete_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_cancel_operation(transport: str = "grpc"): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.CancelOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.cancel_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None -@pytest.mark.asyncio -async def test_cancel_operation_async(transport: str = "grpc_asyncio"): - client = EdgeContainerAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.CancelOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.cancel_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert response is None - -def test_cancel_operation_field_headers(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = operations_pb2.CancelOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - call.return_value = None - - client.cancel_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_cancel_operation_field_headers_async(): - client = EdgeContainerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = operations_pb2.CancelOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - await client.cancel_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] - -def test_cancel_operation_from_dict(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - - response = client.cancel_operation( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_cancel_operation_from_dict_async(): - client = EdgeContainerAsyncClient( - credentials=async_anonymous_credentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.cancel_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_operation(transport: str = "grpc"): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - response = client.get_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) -@pytest.mark.asyncio -async def test_get_operation_async(transport: str = "grpc_asyncio"): - client = EdgeContainerAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_get_operation_field_headers(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = operations_pb2.GetOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - call.return_value = operations_pb2.Operation() - - client.get_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_get_operation_field_headers_async(): - client = EdgeContainerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = operations_pb2.GetOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - await client.get_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] - -def test_get_operation_from_dict(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - - response = client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_get_operation_from_dict_async(): - client = EdgeContainerAsyncClient( - credentials=async_anonymous_credentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_operations(transport: str = "grpc"): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = EdgeContainerAsyncClient( - 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 = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = EdgeContainerAsyncClient( - 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 = EdgeContainerClient( - 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 = EdgeContainerAsyncClient( - credentials=async_anonymous_credentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_operations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.ListOperationsResponse() - ) - response = await client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_locations(transport: str = "grpc"): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = locations_pb2.ListLocationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.ListLocationsResponse() - response = client.list_locations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) -@pytest.mark.asyncio -async def test_list_locations_async(transport: str = "grpc_asyncio"): - client = EdgeContainerAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = locations_pb2.ListLocationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - response = await client.list_locations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - -def test_list_locations_field_headers(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = locations_pb2.ListLocationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - call.return_value = locations_pb2.ListLocationsResponse() - - client.list_locations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_list_locations_field_headers_async(): - client = EdgeContainerAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = locations_pb2.ListLocationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - await client.list_locations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] - -def test_list_locations_from_dict(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.ListLocationsResponse() - - response = client.list_locations( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_list_locations_from_dict_async(): - client = EdgeContainerAsyncClient( - credentials=async_anonymous_credentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - response = await client.list_locations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_location(transport: str = "grpc"): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = locations_pb2.GetLocationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.Location() - response = client.get_location(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.Location) -@pytest.mark.asyncio -async def test_get_location_async(transport: str = "grpc_asyncio"): - client = EdgeContainerAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = locations_pb2.GetLocationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - response = await client.get_location(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - -def test_get_location_field_headers(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials()) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = locations_pb2.GetLocationRequest() - request.name = "locations/abc" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - call.return_value = locations_pb2.Location() - - client.get_location(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations/abc",) in kw["metadata"] -@pytest.mark.asyncio -async def test_get_location_field_headers_async(): - client = EdgeContainerAsyncClient( - credentials=async_anonymous_credentials() - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = locations_pb2.GetLocationRequest() - request.name = "locations/abc" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - await client.get_location(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations/abc",) in kw["metadata"] - -def test_get_location_from_dict(): - client = EdgeContainerClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.Location() - - response = client.get_location( - request={ - "name": "locations/abc", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_get_location_from_dict_async(): - client = EdgeContainerAsyncClient( - credentials=async_anonymous_credentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - response = await client.get_location( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_transport_close_grpc(): - client = EdgeContainerClient( - 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 = EdgeContainerAsyncClient( - 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 = EdgeContainerClient( - 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 = EdgeContainerClient( - 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", [ - (EdgeContainerClient, transports.EdgeContainerGrpcTransport), - (EdgeContainerAsyncClient, transports.EdgeContainerGrpcAsyncIOTransport), -]) -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-edgecontainer/google/cloud/edgecontainer_v1/services/edge_container/transports/rest.py b/packages/google-cloud-edgecontainer/google/cloud/edgecontainer_v1/services/edge_container/transports/rest.py index 312017744563..c2d25b4eb39e 100644 --- a/packages/google-cloud-edgecontainer/google/cloud/edgecontainer_v1/services/edge_container/transports/rest.py +++ b/packages/google-cloud-edgecontainer/google/cloud/edgecontainer_v1/services/edge_container/transports/rest.py @@ -43,7 +43,7 @@ DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, grpc_version=None, - rest_version=requests_version, + rest_version=f"requests@{requests_version}", ) diff --git a/packages/google-cloud-edgecontainer/setup.py b/packages/google-cloud-edgecontainer/setup.py index 7080a9457b31..c7bffe8f09fd 100644 --- a/packages/google-cloud-edgecontainer/setup.py +++ b/packages/google-cloud-edgecontainer/setup.py @@ -46,6 +46,7 @@ # 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", ] extras = {} @@ -84,6 +85,7 @@ "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", ],